循环直到正确输入

时间:2015-10-15 22:06:31

标签: java loops while-loop

System.out.println("What hero are you playing?");
Scanner console = new Scanner(System.in);
Scanner value = new Scanner(System.in);
String character = console.next();
String[] hero = {"x1", "x2", "x3", "x4"};

if(Arrays.asList(hero).contains(character)) {
    System.out.println("hero selected: "+ character);
}
else {
    System.out.println("hero not found");
}

我希望在正确的英雄名字消失之前运行它。如果输入了错误的名称,则应再次询问。

2 个答案:

答案 0 :(得分:0)

尝试这样的事情

    System.out.println("What hero are you playing?");
    Scanner console = new Scanner(System.in);
    Scanner value = new Scanner(System.in);
    String character;
    String[] hero = {"x1", "x2", "x3", "x4"};
    do{
        character = console.next();
        if(Arrays.asList(hero).contains(character)) {
            System.out.println("hero selected: "+ character);
            break;
        }
        else {System.out.println("hero not found");
        }    
    }while (true);

答案 1 :(得分:0)

您正试图循环未知的次数。 (直到满足您定义的条件)。你正在寻找'while'循环。由于您总是希望在输入不正确的名称时执行相同的操作,因此这部分代码应该在while循环中。输入正确的名称后,您需要在代码中移动。因此,将该事件的处理置于循环之外:

System.out.println("What hero are you playing?");
Scanner console = new Scanner(System.in);
/**you have a second scanner, but it's using the same input source. You
should only have one scanner for System.in, maybe call the variable userInput**/
Scanner value = new Scanner(System.in);
//String character = console.next(); you only take input from the user once, this needs to go into a loop.
String character; //do this instead
String[] hero = {"x1", "x2", "x3", "x4"};
while(!Arrays.asList(hero).contains(character = console.next())) {//changed to a while loop. This will keep running until the condition evaluates to false.
    System.out.println("hero not found"); //notice the '!' in the condition check. this means if next console input is NOT contained in the hero array.
}
System.out.println("hero selected: "+ character); //if we're no longer in the loop, it means we found a correct hero name.