2017-04-19 23 views
-1
String[] alpha = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"}; 

我已經制作了包含字母猜測遊戲字母表中所有字母的數組。當用戶輸入的值不在字符串數組中時出錯

我不確定如果用戶在字母表的這些值之外輸入某些內容,我將如何獲得錯誤消息。一個號碼?任何幫助將不勝感激。

+1

正則表達式?像'if(value.equals(「\\ d」))' - >錯誤。或更容易,將數組轉換爲列表並執行如下檢查:'if(!list.contains(value))' - > error – XtremeBaumer

+2

'!input.matches(「[az]」)'應該可以工作。 ..忘記字母表的數組 –

回答

4

如果你想區分大小寫的比較,那麼你可以使用toLowerCase()你可以將它轉換成List和使用contains,例如:

String[] alpha = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"}; 
List<String> list = Arrays.asList(alpha); 
System.out.println(list.contains("a")) 

+0

這已經在給我的錯誤,雖然它輸出26錯誤,當我嘗試輸入一個數字,你會知道如何可以解決這個問題嗎?謝謝您的幫助! – java1234

+0

你可以添加一個例子嗎? –

+0

是否需要System.out.println(list.contains(「a」))代碼行?我已經嘗試了一條if語句,可能會導致重複的錯誤消息。如果(!list.contains(guess)){System.out.println(「Out of range」); – java1234

1

您可以使用此解釋: -

if (! ArrayUtils.contains(alpha, "[i-dont-exist]")) { 
    try{ 
     throw new Exception("Not Found !"); 
    }catch(Exception e){} 
} 

Documentation Here

1

如果目的是檢查的存在裏面收藏了更合理的使用一組由於存取時間元素是constanct

這樣反而

Set<String> set = new HashSet<>();//if not java 8 make it HashSet<String> 
    set.put("a") // do this for all the strings you would like to check 

然後檢查是否字符串存在於這個設置

if(set.contains(str)) //str is the string you want to make sure it exists in the collections 
0

使用這種方法,如果你願意堅持使用數組,而不是其他的數據結構。

  1. 創建如果用戶輸入是存在於陣列中返回true的方法,否則返回假

    public static boolean isValid(String input) { 
        String[] alpha = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", 
         "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", 
         "w", "x", "y", "z"}; 
    
        for(String s: alpha) { 
         if(input.equals(s)) { //use input.equalsIgnoreCase(s) for case insensitive comparison 
          return true; //user input is valid 
         } 
        } 
    
        return false; //user input is not valid 
    } 
    
  2. 在調用方法,只需將用戶輸入傳遞到isValid

    //write some codes here to receive user input..... 
    
    if(!isValid(input)) 
        System.out.println("Oops, you have entered invalid input!"); 
    
相關問題