![](/img/trans.png)
[英]I am trying to create a program that averages numbers, but cannot figure out how to add the user inputted numbers together
[英]I want to add all the values that user inputted in the loop together to let the use know what their total sum is
我想編寫一個代碼,詢問用戶不同的值,然后將它們加在一起。 然后將總和顯示給他們看。 到目前為止,我已經能夠在其中創建多個文本框的情況下進行循環,文本框的數量取決於要添加的值的數量。 但是我不知道如何將它們的所有值相加並顯示出來。
Scanner myInput = new Scanner(System.in);
int addNumber, total;
int num = 0;
System.out.println("Please input how many values you wish to add up together");
addNumber = myInput.nextInt();
for (int numValue =1; numValue <= addNumber; numValue++)
{
int value;
total = num + numValue;
System.out.println("Please input your " + total + " value.");
value = myInput.nextInt();
}
你快到了
首先初始化total
int total = 0;
for (int numValue =1; numValue <= addNumber; numValue++)
{
System.out.println("Please input your " + numValue + " value.");
total += myInput.nextInt();
}
System.out.println ("The total is " + total);
在這段代碼中
total = num + numValue;
您只是將total
的值設置為numValue
因為num
始終為0
在我的代碼中,通過將輸入的值添加到運行總計中,我使用total
來存儲最終答案
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.