while循环。用户输入数字的总和和乘积

时间:2014-08-22 13:27:42

标签: java arrays loops

构建一个程序,使用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

     

线程“main”中的异常java.lang.ArrayIndexOutOfBoundsException:   20       在Case3.main(Case3.java:16)

     

流程已完成。

4 个答案:

答案 0 :(得分:4)

替换

while (x <= list.length) {

while (x < list.length) {

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

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

答案 1 :(得分:2)

问题是x ++所以修改它现在可以工作..

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 :(得分:1)

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

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

while循环必须是,

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

当您处理产品时,产品应该启动为1(不是0)。

答案 3 :(得分:1)

我假设你在问 “线程中的异常”主“java.lang.ArrayIndexOutOfBoundsException” x是一个int数组大小,如果是20,但它的索引从0到19。 使用此停止条件x <= list.length x = 0到20有效地尝试初始化不存在的x [20]。因此更改为'x&lt; list.length'和

product = 1;