gpt4 book ai didi

java - 如何使用字符串变量作为循环目的的条件

转载 作者:行者123 更新时间:2023-11-30 02:47:19 24 4
gpt4 key购买 nike

我试图为我的实践准备一个程序流程图,我遇到了以下情况,用户将输入一个字符串值作为输入"is"或“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”作为输入值。

最佳答案

将 do while 更改为以下内容:

do {
restartOperation = Confirm_Before_Exit();
} while (!restartOperation.equalsIgnoreCase("No") && !restartOperation.equalsIgnoreCase("n"));

关于java - 如何使用字符串变量作为循环目的的条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39810188/

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