2016-06-26 34 views
0

我一直在閱讀驗證的用戶輸入,如果它不是一個數字或者如果輸入不是一個字符,但我如何檢查用戶輸入是我定義的東西他們?驗證輸入字使用Scanner.hasNext()

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]")) 
+1

你不能組成東西。字符串是什麼意思(文檔說)? – user2864740

+0

因爲這不是有效的模式。請參閱:[hasNext(String pattern)](http://www.tutorialspoint.com/java/util/scanner_hasnext_string.htm) – Li357

+2

hmmm嘗試'sc.hasNext(「開胃菜|湯|沙拉|主|甜點」)' – niceman

回答

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!"); 
    } 
} 
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. 
}