JAVA:如何计算循环中用户输入的数字之和(数字存储在同一个变量中)

JAVA:如何计算循环中用户输入的数字之和(数字存储在同一个变量中),java,loops,while-loop,sum,add,Java,Loops,While Loop,Sum,Add,此代码是接收程序的一部分。我将其循环,以便用户可以输入项目价格(最多20个项目)。我需要打印所有项目价格的总和。请注意,所有项目价格都存储在同一个双变量newItemPrice中。这可能吗?如果没有,请告诉我另一种方法 while(x < 20){//maximum of 20 items x++;//item # (x was decalred as an integer of 1) System.out.println("\nEnter new item's pri

此代码是接收程序的一部分。我将其循环,以便用户可以输入项目价格(最多20个项目)。我需要打印所有项目价格的总和。请注意,所有项目价格都存储在同一个双变量
newItemPrice
中。这可能吗?如果没有,请告诉我另一种方法

while(x < 20){//maximum of 20 items

    x++;//item # (x was decalred as an integer of 1)

    System.out.println("\nEnter new item's price");
    Scanner newItemPriceSC = new Scanner(System.in);
    Double newItemPrice = newItemPriceSC.nextDouble();//scans next double (new item's price)

    System.out.println("ITEM # " + x + "\t" + "$" + newItemPrice);//item prices
    System.out.println("\n");

    System.out.println("type \"no more!\" if there are no more items\ntype any other word to continue");
    Scanner continueEnd = new Scanner(System.in);
    String answ = continueEnd.nextLine();       

    if(!(answ.equals("no more!"))){
        continue;
    }


    if(answ.equals("no more!")){
        break;//ends loop
    }

    break;//ends loop (first break; was for a loop inside of this loop)
while(x<20){//最多20项
x++;//项#(x被标为1的整数)
System.out.println(“\n输入新项目的价格”);
Scanner newItemPriceSC=新扫描仪(System.in);
Double newItemPrice=newItemPriceSC.nextDouble();//扫描下一个Double(新项目的价格)
System.out.println(“ITEM#“+x+”\t“+”$”+newItemPrice);//商品价格
System.out.println(“\n”);
System.out.println(“如果没有更多项目,请键入\“no more!\”\n键入任何其他单词以继续”);
Scanner continuend=新扫描仪(System.in);
字符串answ=continueEnd.nextLine();
如果(!(answ.equals(“不再!”)){
持续
}
如果(answ.equals(“不再!”){
break;//结束循环
}
break;//结束循环(第一个break;用于此循环中的一个循环)

您可以使用newItemPrice来累加所有价格,只需将其与当前扫描的价格相加即可

Double newItemPrice += newItemPriceSC.nextDouble();
但是,您将无法在下一行中打印价格


您需要使用newItemPriceSC.nextDouble()的结果引入一个临时变量,以便将其打印出来。如果您失去了打印项目价格的要求,则不需要临时值。

在while开始之前声明一个新变量:

double total = 0;
然后在循环中添加一行代码:

Scanner newItemPriceSC = new Scanner(System.in);//your code
Double newItemPrice = newItemPriceSC.nextDouble();//your code
total +=newItemPrice; //this is the new line

当周期结束时,“total”变量将包含输入的所有价格的总和。

谢谢。我在这个问题上纠缠了一个多小时。但是,如果您不介意,请告诉我您的解决方案是如何工作的。声明“total”有什么意义在循环之外?@ben1123您在循环之外声明此变量,并在该点上等于0。然后循环开始。您将获得下一个双精度(四个示例,5)。然后将下一个数字添加到变量total中。然后循环进入下一个循环,但您的total变量已经等于5但不是零。您将获得另一个double(例如,12),您将其添加到total中,使总数现在等于17(5+12)。依此类推,直到循环停止。表达式“total+=newItemPrice;”表示total=total+newItemPrice。如果在循环中声明total变量,则在循环的每次迭代中都会重新创建并用0初始化它。这意味着您不会从上一次迭代中获得任何剩余信息,这就是为什么在循环外声明此变量。这正是以前发生的情况。不是吗他每隔一段时间就把变量重置为零。这很有意义。再次感谢。