首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >同时循环。用户输入数字的和与积

同时循环。用户输入数字的和与积
EN

Stack Overflow用户
提问于 2014-08-22 13:27:42
回答 4查看 4K关注 0票数 2

生成一个程序,该程序将使用while…生成20个输入数字的和和积。回路结构

条件:

  • 用户只需输入20个号码
  • 得到所有数字的和和积。

我现在的代码是

代码语言:javascript
复制
import java.util.Scanner;

public class Case3 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int[] list = new int[20];
        int sum = 0;
        int product = 0;
        int x = 0;
        int number;

        System.out.print("Add number " + (x + 1) + ": ");
        number = input.nextInt();

        while (x <= list.length) {
             list[x] = number;
             x++;
             System.out.print("Add number " + (x + 1) + ": ");
             number = input.nextInt();
        }

        for (int i = 0; i < x; i++) {
             sum += list[i];
             product *=list[i];
        }

        System.out.println("The sum of all values are: " + sum);
        System.out.println("The product of all values are: " + product);
      }

}  

加1: 1 加2: 2 加3: 3 加4: 4 加5: 5 加6: 6 加7: 7 加8: 8 加9: 9 加10: 10 加11: 11 加12: 12 加13: 13 加14: 14 加15: 15 加16: 16 加17: 17 加18: 18 加19: 19 加20: 20 加21: 21 线程"main“java.lang.ArrayIndexOutOfBoundsException: 20 at Case3.main(Case3.java:16)中的异常 程序已完成。

EN

回答 4

Stack Overflow用户

发布于 2014-08-22 13:30:10

替换

代码语言:javascript
复制
while (x <= list.length) {

使用

代码语言:javascript
复制
while (x < list.length) {

这是因为最后一次迭代将填充数组中的20多个元素。

另外,应该将product初始化为1,而不是0。

票数 4
EN

Stack Overflow用户

发布于 2014-08-22 14:03:36

问题是对x++做了如此修改,现在它起作用了。

代码语言:javascript
复制
public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int[] list = new int[19];
    int sum = 0;
    int product = 1;
    int x = 0;
    int number;
    System.out.print("Add number " + (x + 1) + ": ");
    number = input.nextInt();        
    while (x <list.length) {
         list[x] = number;   
         x++;//1,2,3
         System.out.print("Add number " + (x + 1) + ": ");
         number = input.nextInt();             
    }
    for (int i = 0; i < list.length; i++) {
         sum += list[i];
         product *=list[i];
    }
    System.out.println("The sum of all values are: " + sum);
    System.out.println("The product of all values are: " + product);      
}
票数 2
EN

Stack Overflow用户

发布于 2014-08-22 13:35:38

这两行在while循环之前是不需要的。

代码语言:javascript
复制
System.out.print("Add number " + (x + 1) + ": ");
number = input.nextInt();

虽然循环必须是,

代码语言:javascript
复制
 while (x < list.length) {
     System.out.print("Add number " + (x + 1) + ": ");
     list[x] = number;
     x++;
     number = input.nextInt();
 } 

当您处理产品时,产品应该被初始化为1(而不是0)。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25448196

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档