繁体   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