简体   繁体   English

如何在每个步骤之后检查相同条件,而又不用一遍又一遍地重复Java中的相同代码?

[英]How to check the same condition after each step without repeating the same code over and over in Java?

In my console application, I give the user the option to type "exit" at any point to return to the main menu. 在控制台应用程序中,我为用户提供了随时键入“退出”以返回主菜单的选项。 As the user enters data, i prompt him/her through the console for various things, and collect the data using scanner . 当用户输入数据时,我会通过控制台提示他/她进行各种操作,并使用scanner收集数据。

My question is how can I check to see if the user entered "exit" after each prompt (as opposed to the requested information) without having to use the same if statement after each step? 我的问题是我该如何检查用户是否在每个提示后(而不是所请求的信息)输入了“退出”,而不必在每个步骤之后都使用相同的if语句?

As I see it, any kind of while or for loops are insufficient because they only check the condition at the beginning, when I need to check the condition between inputs, and I need each input/prompt to execute only once per iteration. 如我所见,任何类型的whilefor循环都是不够的,因为它们仅在开始时检查条件,而当我需要检查输入之间的条件时,并且我需要每个输入/提示每次迭代仅执行一次。

The key here is that each prompt/code executed between the checks is DIFFERENT, so loops won't work. 这里的关键是检查之间执行的每个提示/代码都是不同的,因此循环将不起作用。

Here is some example code: 这是一些示例代码:

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;
}

Write a method... 写一个方法...

public boolean isExit(String value) {
    return value.equals("exit");
}

You can then check this method each time... 然后您可以每次检查此方法...

String value = input.nextLine();
if (!isExit(value) {
    // Handle the normal text
} else {
    // Handle the exit operations...
}

You could put additional code in the check, but I would prefer to have an additional method that handles the exit operation...for example... 您可以在检查中放入其他代码,但我希望有一个处理退出操作的其他方法...例如...

String value = input.nextLine();
if (!isExit(value) {
    // Handle the normal text
} else {
    doExit();
}

Take a look at Defining Methods for more details... 查看“ 定义方法”以了解更多详细信息...

Updated 更新

Focus on the idea that a method should do a single job and have no side effects... 专注于一种方法应该完成一项工作且没有副作用的想法...

Having said that, I would setup my code in such away that if the user enters exit at the prompt, the method can exit of it's own accord, without the need for return; 话虽如此,我会这样设置代码:如果用户在提示符下输入exit ,则该方法可以自行退出,而无需return; statement... 声明...

For example... 例如...

public int selectYourMeal() {
    // Prompt...
    int option = -1;
    String value = input.nextLine();
    if (!isExit(value) {
        // Handle the normal text
    } else {
        option = EXIT_OPTION;
    }
    return option;  
}

Where EXIT_OPTION is a special value, which the caller and identify and deal with as it sees fit. 其中EXIT_OPTION是一个特殊值,在调用方认为合适的情况下,调用方可以进行识别和处理。

I'm also old school, in that I was taught that a method should have one entry and one exit point, you really want to avoid having multiple exit points within your methods, as it becomes very difficult to follow the logic... 我也是老派,因为我被教导一种方法应该有一个入口和一个出口点,您真的想避免方法中有多个出口点,因为遵循逻辑变得非常困难...

If I understand you correctly, I recommend a do-while loop. 如果我对您的理解正确,建议您进行一次do-while循环。 It will first take text the first time, perform an action, and if it is exit it will break the loop, otherwise it will repeat. 第一次将第一次获取文本,执行一个操作,如果退出,它将中断循环,否则将重复执行。

 do{
 text = input.nextLine();

 //whatever code you want here to perform with input

 }while(!(text.equals("exit"));

I would suggest you use an List<String> of words. 我建议您使用单词的List<String> You can return it. 您可以return Also, it's a really bad idea to close a Scanner wrapping System.in , once you do you cannot re-open it. 另外,关闭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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在不一遍又一遍地编写相同代码的情况下为多个 JTextFields 提供 addKeyListener() - How to provide addKeyListener() to a multiple JTextFields without writing the same code over and over again Java服务器反复接收相同的数据 - Java server receiving same data over and over 一遍又一遍地检查值递增的相同条件 - Checking for same condition with incremented value over and over again 在 Android Studio 中调试应用程序时如何单步执行或跳过代码 - How to step into or step over code while debugging application in Android Studio 如何正确处理 Java 中同一个 Socket 上的多个操作? - How to properly handle multiple operations over same Socket in Java? Java 扫描仪一遍又一遍地读取同一个文件 - Java Scanner reading same file over and over again 在Java中同时迭代两个TreeMap - Iterate over two TreeMap at the same time in Java Java 在另一个音频上播放相同的音频 - Java playing the same audio over the another one 用于在同一列表上循环两次的 Java Streams - Java Streams for looping twice over same list 无法进入Java源代码。 “进入”某种方式就像“越过” - can't step into java source code. “step into” somehow act like “step over”
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM