java 如何询问用户是否要再次运行程序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27198119/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to ask user if they want to run program again or not?
提问by pikachu7
I already have the code for the scanner but I don't know how to make the code so that you can ask the user whether to run the program again or not. My program is for the PigLatin(a constructed language game in which words in English are altered according to a simple set of rules).
我已经有了扫描仪的代码,但我不知道如何制作代码,以便您可以询问用户是否再次运行该程序。我的程序是针对PigLatin(一种构建的语言游戏,其中根据一组简单的规则更改英语单词)。
I have to make it so that it will ask the user if he/she wants to translate another phrase and wait for the user to enter "Y" or "y" as yes, "n" or "N" as no. If yes, run program again. If no, exit the program. For all other letters, reject it and ask the user to enter only "y" or "n".
我必须这样做,以便它会询问用户他/她是否想翻译另一个短语,并等待用户输入“Y”或“y”为是,“n”或“N”为否。如果是,再次运行程序。如果没有,退出程序。对于所有其他字母,拒绝它并要求用户仅输入“y”或“n”。
public static void main (String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter an English phrase or sentence :");
String sentence = keyboard.nextLine();
System.out.println("\"" +sentence+ "\"" + " ");
Scanner word = new Scanner(sentence);
System.out.println("In PigLatin that would be: ");
while (word.hasNext()) {
String pigLatin = word.next();
System.out.print(convertPigLatinWord(pigLatin));
}
}
回答by Alex K
Just use a while
loop. Until you say "no" at the end, stop will be false
, so !stop
will be true
, and you'll keep looping.
只需使用一个while
循环。直到你在最后说“不”,停止会false
,所以!stop
会true
,你会不断循环。
Scanner scan = new Scanner(System.in);
boolean stop = false;
while(!stop) {
//do whatever
System.out.println("Would you like to continue? (yes or no)");
String s = scan.nextLine();
if(s.equals("no")) {
stop = true;
}
}