我目前正在研究一个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;
}
}
}
答案 0 :(得分:3)
break
循环中的for
导致循环退出。在这里,这导致循环在第一次迭代时退出,这几乎肯定不是您想要的。
将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
。
答案 1 :(得分:0)
代码中的问题是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);
}
}