【发布时间】:2014-10-16 09:03:27
【问题描述】:
构建一个程序,该程序将使用 while...循环结构生成 20 个输入数字的和和乘积。
条件:
- 用户只需输入 20 个数字
- 并得到所有数字的总和和乘积。
我现在的代码是这样的
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
线程“主”java.lang.ArrayIndexOutOfBoundsException 中的异常: 20 在 Case3.main(Case3.java:16)
过程完成。
【问题讨论】:
-
您刚刚发现当您尝试将 21 个数字放入大小为 20 的数组中时会发生什么