使用Scanner.hasNext()

时间:2016-06-26 18:23:28

标签: java validation java.util.scanner

如果用户输入不是数字或者输入不是字符,我一直在阅读用户输入的验证,但是如何检查用户输入是否是我为他们定义的内容?

System.out.println("What meal would you like to eat?"
        + " (appetizer, soup, salad, main, or dessert)");
String meal = console.next();

我看到了

Scanner sc = new Scanner(System.in);
System.out.println("Please enter a vowel, lowercase!");
while (!sc.hasNext("[aeiou]")) {
    System.out.println("That's not a vowel!");
    sc.next();
}

但是当我改变时编译器不喜欢

(!sc.hasNext("[aeiou]")) 

(!sc.hasNext("[appetizer, soup, salad, main, dessert]"))

2 个答案:

答案 0 :(得分:0)

也许您想以这种方式尝试(您也可以使用枚举而不是HashSet):

System.out.println("What meal would you like to eat?"
        + " (appetizer, soup, salad, main, or dessert)");
HashSet<String> vowels = new HashSet<String>();
vowels.add("appetizer");
vowels.add("soup");
vowels.add("salad");
vowels.add("main");
vowels.add("dessert");
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a vowel, lowercase!");
while (sc.hasNext()) {
    String vowel = sc.next();
    if (vowels.contains(vowel)) {
        System.out.println("That's a vowel!");
    } else {
        System.out.println("That's not a vowel!");
    }
}

答案 1 :(得分:0)

您可以执行以下操作。检查用户的输入是否在允许值数组中。

List<String> meals = Arrays.asList(
    new String[]{"appetizer", "soup", "salad","main","dessert"});
String meal = console.next().toLowercase();
if(meals.contains(meal)){
    //Do what you want with correct input.
}