gpt4 book ai didi

java - 使用 int 变量控制 Do...While() 循环不起作用

转载 作者:行者123 更新时间:2023-12-02 01:18:24 25 4
gpt4 key购买 nike

编辑:问题是我没有在其外部声明变量

我的循环无法将 int 解析为变量。

不能尝试其他类型的变量,这必须是整数。

        do {
System.out.println("Would you like to add any snacks? ");
System.out.println("1: ($5) Large Popcorn");
System.out.println("2: ($0) Nothing Else");
int snackChoice = input.nextInt();

System.out.println("How many of option " + snackChoice + " would you like? ");
System.out.println("1: One");
System.out.println("2: Two");
System.out.println("3: Three");
System.out.println("4: Four");
System.out.println("5: Five");
int snackAmount = input.nextInt();

switch (snackChoice) {
case 1:
cost = cost + 5 * snackAmount;
System.out.println("Your total before tax will be: $" + cost + (5 * snackAmount));
break;

default:
System.out.println("Not a valid option.");
break;

}
}
while(snackChoice != 9);

其余部分:https://pastebin.com/Y6Xd24D0

它有效。实际结果:没有。

错误:snackChoice 无法解析为变量

最佳答案

do...while 循环是一个代码块,这意味着在其中定义的变量在代码块之外是看不到的。 while 部分位于 block 之外,因此它看不到 snackChoice

只需在do...while之前定义int SnackChoice不在其中:

int snackChoice;
do {
System.out.println("Would you like to add any snacks? ");
System.out.println("1: ($5) Large Popcorn");
System.out.println("2: ($0) Nothing Else");
snackChoice = input.nextInt();

System.out.println("How many of option " + snackChoice + " would you like? ");
System.out.println("1: One");
System.out.println("2: Two");
System.out.println("3: Three");
System.out.println("4: Four");
System.out.println("5: Five");
int snackAmount = input.nextInt();

switch (snackChoice) {
case 1:
cost = cost + 5 * snackAmount;
System.out.println("Your total before tax will be: $" + cost + (5 * snackAmount));
break;

default:
System.out.println("Not a valid option.");
break;

}
}
while(snackChoice != 9);

关于java - 使用 int 变量控制 Do...While() 循环不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58176487/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com