为什么我的java程序会跳过我的输入并挂起IF语句?

时间:2017-09-24 05:35:19

标签: java

我的程序中的其他所有内容都有效,除了这个单一方法,它会跳过sc.next()然后挂起我的if。

public static String getChoice() {
    boolean choiceSelector = false;

    // construct a Scanner object for getting input
    Scanner sc = new Scanner(System.in);

    System.out.println("Do you wish to continue? Y/N");
    String choice = " ";

    do{
    choice = sc.next();

    if(choice.equalsIgnoreCase("Y")){
        choice="Y";
        choiceSelector = true;
    }
    if(choice.equalsIgnoreCase("N")){
        choice="N";
        choiceSelector = true;
    } else
        choice = sc.next("Please enter a correct value.");

    } while(choiceSelector == false);

    return choice;
}//end getChoice

1 个答案:

答案 0 :(得分:0)

可能会添加另一个else,因为即使输入最初为Y,您也要求他们提供正确的值:

if(choice.equalsIgnoreCase("Y")){
    choice="Y";
    choiceSelector = true;
} else if(choice.equalsIgnoreCase("N"))...

并打破

choice = sc.next("Please enter a correct value."); // not a valid pattern provided as an input here

作为

System.out.println("Please enter a correct value.");
choice = sc.next();

return choiceSelector; // the boolean value