繁体   English   中英

Java-汇总数组列表值

[英]Java - summing up Array list values

我正在建立一个数组,询问您有多少个不同的输入,然后允许您输入每个输入。 最后,我想对它们进行总结,但是我总是遇到错误。 同样,当我超过5个输入时,我也会丢失一个.....例如,当我回答第一个问题时:输入“ 10”。 当我开始添加不同的数字时,它会停在9点。 请帮忙。

public static void main(String [] args){扫描仪输入=新的Scanner(System.in);

    System.out.println("Please enter the number of courses you have left: ");
    int size = input.nextInt();
    int[] numArr = new int[size];
    System.out.println("Enter the number of CUs for each course: ");
    for (int i=0; i<numArr.length; i++)
    {
        numArr[i] = input.nextInt();
    }
    int totalSum = numArr + totalSum;
    System.out.print("The sum of the numbers is: " + totalSum);

将逻辑和代码更改为以下内容:

Scanner input = new Scanner(System.in);

System.out.println("Please enter the number of courses you have left: ");
int size = input.nextInt();
System.out.println("Enter the number of CUs for each course: ");
int totalSum = 0;
for (int i = 0; i < size; i++) {

    totalSum+=input.nextInt();
}

System.out.print("The sum of the numbers is: " + totalSum);

尝试

System.out.println("Please enter the number of courses you have left: ");
int size = input.nextInt();

int totalSum = 0;
for (int i=0; i< size; i++)
{
    System.out.println("Enter the number of CUs for each course: ");
    int cuNum = input.nextInt();
    totalSum += cuNum ;
}

System.out.print("The sum of the numbers is: " + totalSum);

可以肯定您的预期结果是

public static void main(String[] args) { 
Scanner input = new Scanner(System.in);
System.out.println("Please enter the number of courses you have left: ");
int size = input.nextInt();
int[] numArr = new int[size];
int totalSum = 0;
System.out.println("Enter the number of CUs for each course: ");
for (int i=0; i<numArr.length; i++)
{
    numArr[i] = input.nextInt();
    totalSum += numArr[i];
}

    System.out.print("The sum of the numbers is: " + totalSum);
}

您的其他代码无法正常运行主要是因为

int totalSum = numArr + totalSum;

您不能定义totalSum来定义自己! 而且您不能只使用numArr ... numArr是一个数组-您必须访问索引,而不是整个数组!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM