在我的控制台应用程序中,我为用户提供键入" exit"在任何时候返回主菜单。当用户输入数据时,我会通过控制台提示他/她进行各种操作,并使用scanner
收集数据。
我的问题是如何检查用户是否输入"退出"在每个提示之后(而不是所请求的信息),而不必在每个步骤之后使用相同的if语句?
在我看来,任何类型的while
或for
循环都是不够的,因为它们只检查开始时的条件,当我需要检查输入之间的条件时,我需要每个输入/提示每次迭代只执行一次。
这里的关键是在支票之间执行的每个提示/代码都是不同的,所以循环不起作用。
以下是一些示例代码:
String first;
String second;
Scanner input = new Scanner(System.in);
//prompt user for input
first = input.nextline();
if(first.equals("exit")){
//return to start menu
input.close();
return;
}
//prompt user for DIFFERENT input
second = input.nextline()
if(second.equals("exit")){
//return to start menu
input.close();
return;
}
答案 0 :(得分:2)
写一个方法......
public boolean isExit(String value) {
return value.equals("exit");
}
然后,您可以每次检查此方法......
String value = input.nextLine();
if (!isExit(value) {
// Handle the normal text
} else {
// Handle the exit operations...
}
您可以在支票中添加其他代码,但我更愿意使用其他方法来处理退出操作......例如......
String value = input.nextLine();
if (!isExit(value) {
// Handle the normal text
} else {
doExit();
}
请查看Defining Methods了解更多详情......
<强>更新强>
专注于一种方法应该完成一项工作并且没有副作用的想法......
话虽如此,我会设置我的代码,如果用户在提示符处输入exit
,该方法可以自行退出,而不需要return;
语句。
例如......
public int selectYourMeal() {
// Prompt...
int option = -1;
String value = input.nextLine();
if (!isExit(value) {
// Handle the normal text
} else {
option = EXIT_OPTION;
}
return option;
}
EXIT_OPTION
是一个特殊值,调用者可以根据需要识别和处理。
我也是老派,因为我被教导一个方法应该有一个入口和一个出口点,你真的想避免在你的方法中有多个出口点,因为它很难遵循逻辑。 ..
答案 1 :(得分:2)
如果我理解正确,我建议使用do-while循环。它将首次采用文本,执行一个动作,如果它是退出,它将打破循环,否则它将重复。
do{
text = input.nextLine();
//whatever code you want here to perform with input
}while(!(text.equals("exit"));
答案 2 :(得分:0)
我建议您使用List<String>
个单词。你可以return
。此外,关闭Scanner
包裹System.in
是一个非常糟糕的主意,一旦你做到了,就无法重新打开它。
List<String> words = new ArrayList<>();
Scanner input = new Scanner(System.in);
for (int i = 0; input.hasNextLine(); i++) {
String line = input.nextLine();
words.add(line);
if (line.equalsIgnoreCase("exit")) {
break;
}
}
System.out.println(words);
return words;