【发布时间】:2020-05-26 12:39:24
【问题描述】:
我目前正在学习 Java,我需要在我的 do-while 循环中添加每个实例的值。有什么方法可以存储这些值,这样就不会在每个循环中都被覆盖?
import java.util.Scanner;
class Main{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
char userChar;
do {
System.out.println("Apples are $10");
System.out.println("How many do you want?");
int itemQty = input.nextInt();
System.out.println("Do you wish to buy more? (y/n)");
userChar = input.next()charAt(0);
} while (userChar == 'y');
// all values entered by the user needs to be added
System.out.println("The total is: $" + (itemQty*10));
}
}
【问题讨论】:
-
将
int itemQty移出循环,然后写itemQty += input.nextInt(),这样您就可以创建一个可以在最后打印的苹果总和 -
困扰我好几个小时了!!它现在可以工作了,非常感谢伙计!!!
标签: java loops java.util.scanner store do-while