简体   繁体   English

如何创建一个检查输入验证的do-while循环

[英]How to make a do-while loop that checks for input validation

For example, I want a loop that prints out "Do you want to watch a movie?" 例如,我想要一个打印出“你想看电影吗?”的循环。 until the user enters "yes". 直到用户输入“是”。

Here's what I have so far: 这是我到目前为止所拥有的:

import java.util.Scanner;

public class Testing {
    public static void main(String args[]){
        Scanner scan = new Scanner(System.in);
        do {
           System.out.println("Do you want to watch a movie?");
           scan.nextLine();
           String Answer = scan.next();
        }
        while (!Answer.equals("yes"));

You have to define the Answer variable outside the loop scope: 您必须在循环范围之外定义Answer变量:

Scanner scan = new Scanner(System.in);
String answer;
do {
    System.out.println("Do you want to watch a movie?");
    // scan.nextLine(); you don't need this
    answer = scan.next();
}
while (!answer.equals("yes"));

Also use proper Java naming conventions: variable names should be lowerCamelCase. 还使用适当的Java命名约定:变量名称应为lowerCamelCase。

the test condition is out of the scope of the { and } where you read it, so move the declaration of String answer (lowcase) to before of the do statement so we can test it outside the block (the while instruction is out of itand is the condition to execute the block again). 测试条件超出了你读取它的{和}的范围,所以将String answer的声明(低位)移到do语句之前,这样我们就可以在块外面测试它(while指令不在它之外)是再次执行块的条件)。

And, nextLine() returns and consume the value readed, the result will be it. 而且,nextLine()返回并消耗readed值,结果就是它。

    String answer;
    do {
       System.out.println("Do you want to watch a movie?");
       answer = scan.nextLine();
    } while(!answer.equals("yes"));

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

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