循环直到输入某个字符?

时间:2014-11-10 19:20:38

标签: java loops

我摘录了我需要处理的代码,我知道它的标准做法是发布所有代码,但我不认为它需要在这里。

    if(playerValue > 10 && playerValue < 21){

            System.out.println("Players Value so far " + playerValue + ", Do you want to draw another card? Y/N");
            //  input a y or n answer
            decision = sob.next();

            if(decision.equals("Y") || decision.equals("y")){
                continue;

            }else if(decision.equals("N") || decision.equals("n")){
                break;
            }

        }
    }

如何将此语句更改为接受Y或N,如果我输入任何内容将它们设为两个字符,它将继续,就像我按下Y一样。

3 个答案:

答案 0 :(得分:1)

你应该有一个其他案例:

if(playerValue > 10 && playerValue < 21){

            System.out.println("Players Value so far " + playerValue + ", Do you want to draw another card? Y/N");
            //  input a y or n answer
            decision = sob.next();

            if(decision.equalsIgnoreCase("Y")){
                continue;

            }else if(decision.equalsIgnoreCase("N")){
                break;
            }
            else
            {
                 //whatever you want to happen if they don't enter either y or n
            }

        }
    }

也许在else中有另一个循环说请输入一个有效的输入并保持循环,直到它们给出有效的输入...

答案 1 :(得分:0)

以下是如何将代码更改为&#34;坚持&#34;在用户上输入YN

static void readYesOrNo(Scanner input) {
    String str;
    while (true) {
        str = input.next();
        if (str.equalsIgnoreCase("y")) {
            return true;
        }
        if (str.equalsIgnoreCase("n")) {
            return false;
        }
        System.out.println("Please enter Y or N");
    }
}

我将此代码放入静态方法中,以便您可以在其他地方重用它。现在,您可以在代码中使用此方法,如下所示:

if(playerValue > 10 && playerValue < 21){
    System.out.println("Players Value so far " + playerValue + ", Do you want to draw another card? Y/N");
    if (readYesOrNo(sob)) {
        continue;
    }
    break;
}

答案 2 :(得分:0)

你可以试试这个:

        if(playerValue > 10 && playerValue < 21){
          while(true){
          System.out.println("Players Value so far " + playerValue + ", Do you want to draw another card? Y/N");
          //  input a y or n answer

         decision=sob.next();
         if(decision!=null && (decision.equalsIgnoreCase("y")||decision.equalsIgnoreCase("n"))){
            break;
        }
        else{
            System.out.println("please answer with Either y or n");
            continue;
          }
        }//end of while loop

        //put your code here 
     }