[英]Java - Program not breaking out of loop?
while (choice != 7) {
System.out.println("--- Mathematical Calculator ---");
System.out.println("");
System.out.println("Pick an operation from the list - Use nos. 1 to 7");
System.out.println("1) Multiplication");
System.out.println("2) Division");
System.out.println("3) Addition");
System.out.println("4) Subtraction");
System.out.println("5) Find the area of a regular object");
System.out.println("6) Find the volume of a regular object");
System.out.println("7) Exit");
choice = userInput.nextInt();
switch (choice) {
case 1: {
System.out.println("");
System.out.println("You have chosen multiplication");
System.out.println("Enter a number");
double num1 = userInput.nextDouble();
System.out.println("Enter another number");
double num2 = userInput.nextDouble();
double num3 = num1 * num2;
System.out.println(num1 + " * " + num2 + " = " + num3);
num1 = num3;
while (choice2 != 5 || choice2 != 6) {
System.out.println(""); System.out.println("");
System.out.println("If you would like to build on the answer obtained - pick an operation from the list - Use nos. 1 to 4");
System.out.println("Else press 5 to return to the main menu");
System.out.println("1) Multiplication");
System.out.println("2) Division");
System.out.println("3) Addition");
System.out.println("4) Subtraction");
System.out.println("5) Start new calculation");
System.out.println("6) Exit");
choice2 = userInput.nextInt();
switch (choice2) {
case 1:
{
System.out.println("Enter number");
num2 = userInput.nextDouble();
num3 = num1 * num2;
System.out.println(num1 + " * " + num2 + " = " + num3);
num1 = num3;
break;
}
case 2:
{
System.out.println("Enter number");
num2 = userInput.nextDouble();
num3 = num1 / num2;
System.out.println(num1 + " / " + num2 + " = " + num3);
num1 = num3;
reak;
}
case 3:
{
System.out.println("Enter number");
num2 = userInput.nextDouble();
num3 = num1 + num2;
System.out.println(num1 + " + " + num2 + " = " + num3);
num1 = num3;
break;
}
case 4:
{
System.out.println("Enter number");
num2 = userInput.nextDouble();
num3 = num1 - num2;
System.out.println(num1 + " - " + num2 + " = " + num3);
num1 = num3;
break;
}
case 5: choice = 0; break;
case 6: choice = 7; break;
default: System.out.println("Invalid choice");
}
choice2 = 0;
}
break;
}
我發布了一小段代碼。 我的問題是,當我在第二個查詢( choice2
)中輸入5或6時,我的程序繼續循環而不是退出循環並返回主菜單/終止程序。
希望得到一些關於我做錯的反饋。
你的while (choice2 != 5 || choice2 != 6)
是錯誤的,因為它總會導致true。 如果choice2為5,則第二個子句為真。
更不用說你總是在循環結束時將choice2設置為0,所以即使你替換了||
,循環也將永遠繼續 用&&
。
條件choice2 != 5 || choice2 != 6
choice2 != 5 || choice2 != 6
始終為true,因為沒有數字同時等於5和6。
如果您想在輸入5或6時跳出循環,請使用&&
代替:
while (choice2 != 5 && choice2 != 6)
確保在繼續下一次循環迭代之前設置choice2
。
請注意,您可以使用帶標簽的break構造從switch
語句中跳出循環:
calc: // Label the loop for using labeled break
while (true) {
...
switch(...) {
case 1:
break; // This will exit the switch
...
case 6: break calc; // This will exit the loop
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.