简体   繁体   English

不断要求用户输入

[英]Continuously ask for a user input

I have two available options for a user to input, and what I am trying to accomplish is if the user does not enter either of the inputs the program will continuously ask them again until they enter a valid one. 我有两个可用的选项供用户输入,而我要完成的工作是,如果用户未输入任何一个输入,则程序将不断询问他们,直到他们输入有效的输入为止。 Here is the code right now 这是现在的代码

String userLIB = user_input.next();
    if (userLIB.contentEquals(UBC.acro)){
        printDetails(UBC);
    } else {
        if (userLIB.contentEquals(ORL.acro)){
            printDetails(ORL);
        } else {
            while (!userLIB.contentEquals(UBC.acro) || !userLIB.contentEquals(ORL.acro)){
            System.out.println("Invalid input");
            break;
            }
        }
    }

I have a break to keep the code from looping the "Invalid input" indefinetly but it just ends the program right now which isn't what I want to happen. 我有一个休息时间,以防止代码无限期地循环“无效输入”,但它现在刚刚结束程序,这不是我想要发生的事情。 Is there a way to make the program go back to the start of the if statement? 有没有办法使程序回到if语句的开头?

You're breaking your code when the Invalid input condition is met. 满足无效输入条件时,您正在破坏代码。 Do as following, 执行以下操作

String userLIB = "";
do {
    userLIB = user_input.next();
    if (userLIB.contentEquals(UBC.acro)){
        printDetails(UBC);
    } else if (userLIB.contentEquals(ORL.acro)) {
        printDetails(ORL);
    } else {
        System.out.println("Invalid input. Try again!");
    }
} while (!userLIB.contentEquals(UBC.acro) || !userLIB.contentEquals(ORL.acro));

This, tries to get the only 2 possible inputs and terminate the loop. 这将尝试获取仅有的2个可能的输入并终止循环。 Else will loop again and again, until the required input is provided. 其他将反复循环,直到提供所需的输入为止。

I figured it out with the help of @Carcigenicate, I put a while loop outside of the whole code and then put a userLIB = user_input.next(); 我在@Carcigenicate的帮助下弄清楚了,我在整个代码之外放了一个while循环,然后放了一个userLIB = user_input.next();。 inside of the incorrect if statement. 错误的if语句中。 Also thanks to @Sridhar for giving an answer that also works 也感谢@Sridhar提供的答案也有效

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM