Java:如何让Scanner对象忽略不需要的/无效的输入?

时间:2017-03-08 05:44:32

标签: java java.util.scanner

我正在尝试设置一个简单的文本树,它以单字符(y / n)或与打印列表(1-4)对应的整数读取。我想知道最简单的方法是让程序忽略与给定选项不对应的用户输入,如下所示:

import java.util.Scanner;

public class simpleMenu
{
    Scanner sc = new Scanner(System.in);
    String choicePick;

    public static void main(String[] args)
    {
        System.out.println("Would you like to continue? (y/n)");
        choicePick = sc.next();

        if(choicePick.equals("y"))
        {
            // The program continues.
        } 
        else if(choicePick.equals("n"))
        { 
            // The program closes.
        } 
        else 
        {
            /* 
            The scanner ignores the input, ideally without having to restate the question.
            The program does not quit or move on until "y" or "n" is entered.
            */ 
        }
    }
}

如果你可以帮我实现一个'奖励积分?选项带我进入上一个选择。

1 个答案:

答案 0 :(得分:0)

虽然下一个字符串不是Y或N sc.next(),直到它为止。然后使用该字符串。