我目前正在編寫一個(gè) java 代碼,它從用戶那里獲取輸入并輸出 arraylist 的大小、輸入的數(shù)字總和、輸入的平均值和最大數(shù)量。我無法完成總和,因?yàn)?for 循環(huán)沒有計(jì)算結(jié)果。我將不勝感激任何建議。我的代碼如下。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; } }}
2 回答

慕勒3428872
TA貢獻(xiàn)1848條經(jīng)驗(yàn) 獲得超6個(gè)贊
將break在for循環(huán)將導(dǎo)致循環(huán)退出。在這里,它導(dǎo)致循環(huán)在第一次迭代時(shí)退出,這幾乎肯定不是您想要的。
將println外部移動(dòng)到循環(huán)中,并刪除break:
for (double sum : inputs) {
total += sum;
}
System.out.println("The sum of numbers entered is " + total);
這允許for循環(huán)在計(jì)算總和時(shí)迭代整個(gè)列表,以便您可以打印它而不是過早退出。
還要注意的是:
inputs.size(); // get size of input
做什么都沒有用。size返回 的大小inputs,然后您對(duì)該數(shù)字不執(zhí)行任何操作,因此它丟失了。您應(yīng)該刪除該行,因?yàn)閟ize無論如何您都會(huì)在下一行再次調(diào)用。
添加回答
舉報(bào)
0/150
提交
取消