簡體   English   中英

用戶輸入不在字符串數組中的值時出錯

[英]Error when the user enters values not in String Array

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並使用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"))

如果要進行不區分大小寫的比較,則可以使用toLowerCase()

您可以使用一個字符數組。 這里給出了示例https://www.javatpoint.com/java-string-tochararray 然后,您可以使用indexof方法查看用戶輸入的值是否有效,如此處所述, 如何檢查字符串中是否出現單個字符?

您可以使用以下方法:

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

這里的文件

如果檢查集合中元素是否存在的目的是更合理的做法是使用集合,因為訪問時間很長

所以與其

   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

如果您想堅持使用數組而不是其他數據結構,請使用此方法。

  1. 創建一個如果數組中存在用戶輸入則返回true的方法,否則返回false

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM