[英]Output sum of element entered by user to an 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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.