我正在嘗試爲我的練習編寫一個程序流程圖,其中我遇到以下情況對我來說需要用戶輸入字符串值作爲輸入「是「或‘Y’和‘否’或‘N’,並根據其輸入端的應用程序將終止或從某一點重新啓動到現在我在我的腦海裏有這個作爲一個例子如何使用字符串變量作爲循環目的的條件
public class ApplicationName {
public static void main(String args[]) {
String restartOperation;
do {
restartOperation = Confirm_Before_Exit();
} while (!restartOperation.equals("No"));
//Rest of code
}
public static void Some_Operation() {
//Executed when called before closing application
}
public static String Confirm_Before_Exit() {
Scanner inputData = new Scanner(System.in);
String answer;
System.out.println("Do you want to perform another operation ?" + " " + "Y" + " " + "N");
answer = inputData.nextLine();
switch (answer) {
case "Y":
case "Yes":
Some_Operation();
break;
default:
System.out.println("Good Bye !");
}
return answer;
}
}
這工作,直到用戶沒有給出輸入爲「否」,但顯然如果輸入「N」或可能小「n」或甚至「否」不會工作,但對於時間我只是試圖將「否」和「N」作爲輸入值。
它再次陷入無限循環,並且不斷詢問即使輸入「n」或「no」 –
@MehulChachada更新了答案。 '||'需要用'&&'代替。試試看。它現在的作品 –
它的作品謝謝! 〜 –