编辑:问题是我没有在变量外声明变量
我的循环无法将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 cannot be resolved to a variable
答案 0 :(得分:2)
do...while
循环是一个代码块,这意味着无法在该块外部看到其中定义的变量。 while
部分在块之外,因此看不到snackChoice
。
只需在int snackChoice
之前之前定义do...while
,不在其中:
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);