[英]How do I make my loop stop
我試圖停止計算器程序的循環,但是不允許使用breaks或system.exit。 我該如何停止我的循環,僅輸入5菜單? 另外,如果我輸入“ n”來詢問是否要再次使用計算器,該如何退出程序? PS我正在使用Java。
public static void main (String args []) {
String MainMenu = " Calculator Options \n\n1. Addition\n2" +
" Subtraction\n3. Multiplication\n4. Division\n5. Exit";
menu (MainMenu);
while (true) {
String YesorNo = JOptionPane.showInputDialog("Would You Like to Use the Calculator Again (y / n)? ");
if (YesorNo.equals ("y")) {
menu (MainMenu);
}
if (YesorNo.equals ("n")) {
}
}
}
public static int menu (String info) {
String choice = JOptionPane.showInputDialog (info);
if (choice.equals ("1"))
return Addition();
else if (choice.equals ("2"))
return Subtraction();
else if (choice.equals ("3"))
return Multiplication();
else if (choice.equals ("4"))
return Division();
else
return 0;
}
使用break
關鍵字。
if (YesorNo.equals ("n")) {
break;
}
或者將條件放入while-loop
並使用關鍵字do
。
do {
// code & blaaa .. blaaa & code
} while (YesorNo.equals("y"));
要回答你們兩個問題:
您只需要使用do-while
循環並在其中包含兩個條件即可。 但是,使用您當前的實現,這種方法將不會100%地起作用。
原因是,您還從menu
返回操作以及結果。
首先,這就是循環的外觀。
do {
String YesorNo = JOptionPane.showInputDialog ("Would You Like to Use the Calculator Again (y / n)? ");
int menuReturn = menu (MainMenu);
} while (YesorNo.equals("y") || menuReturn != 0);
那就是可行的方法,如果menu
方法不在值0-4
內,則它會返回0
。 但是,如果任何數學運算的結果為0
什么? 您還將關閉計算器。 此時,您可能需要更改menu
功能。
private static int result = 0;
public static int menu (String info) {
String choice = JOptionPane.showInputDialog (info);
if (choice.equals ("1")) {
result = Addition();
return 1;
}
else if (choice.equals ("2")) {
result = Subtraction();
return 1;
}
else if (choice.equals ("3")) {
result = Multiplication();
return 1;
}
else if (choice.equals ("4")) {
result = Division();
return 1;
}
else if (choice.equals("5"))
return -1;
else
return 0;
您的循環設計現在將變為如下所示。
do {
String YesorNo = JOptionPane.showInputDialog ("Would You Like to Use the Calculator Again (y / n)? ");
int menuReturn = menu (MainMenu);
// Work with the result now
if (menuReturn == 0) // invalid input;
} while (YesorNo.equals("y") || menuReturn != -1);
但是為了使其完全符合OOP原則,您可能必須重寫更多的代碼,然后再顯示答案中所示的代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.