输出用户输入到 ArrayList Java 的元素的总和



我目前正在研究一个Java代码,该代码从用户那里获取输入并输出arraylist的大小,输入的数字总和,输入的平均值和最大数量。 我无法完成总和,因为 for 循环没有计算结果。我将不胜感激任何建议。我的代码如下。

import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// write your code here
double size = 0;
double a = -999;
double total = 0;
Scanner in = new Scanner(System.in); // scanner object for user input
ArrayList<Double> inputs = new ArrayList<Double>();
System.out.println("Enter a number, to terminate enter -999 :");
while (in.hasNextDouble()) {
//assign the nextDouble to a variable
double tmp = in.nextDouble();
//test the variable
if (tmp != a) {
//add the variable
//if you want to add -999 to the inputs then this next line above the test.
inputs.add(tmp);
System.out.println("Enter a number, to terminate enter -999 :");
} else {
inputs.size(); // get size of input
System.out.println("Numbers entered: " + inputs.size());
break;
}
}
for (double sum : inputs) {
total += sum;
System.out.println("The sum of numbers entered is " + total);
break;
}
}
}

for循环中的break会导致循环退出。在这里,它导致循环在第一次迭代时退出,这几乎肯定不是您想要的。

println移出循环,并删除break

for (double sum : inputs) {
total += sum;
}
System.out.println("The sum of numbers entered is " + total);

这允许for循环在计算总和时迭代整个列表,以便您可以在之后打印它,而不是过早退出。


另请注意:

inputs.size(); // get size of input

没有做任何有用的事情。size返回inputs的大小,那么你不会对该数字执行任何操作,因此它会丢失。您应该删除该行,因为无论如何您都会在下一行再次调用size

代码中遇到的问题是 for 循环中有中断条件

正确的代码如下

import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// write your code here
double size = 0;
double a = -999;
double total = 0;
Scanner in = new Scanner(System.in); // scanner object for user input
ArrayList<Double> inputs = new ArrayList<Double>();
System.out.println("Enter a number, to terminate enter -999 :");
while (in.hasNextDouble()) {
//assign the nextDouble to a variable
double tmp = in.nextDouble();
//test the variable
if (tmp != a) {
//add the variable
//if you want to add -999 to the inputs then this next line above the test.
inputs.add(tmp);
System.out.println("Enter a number, to terminate enter -999 :");
} else {
inputs.size(); // get size of input
System.out.println("Numbers entered: " + inputs.size());
break;
}
}
for (double sum : inputs) {
total += sum;
}
System.out.println("The sum of numbers entered is " + total);
}
}

最新更新