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"};
我已经制作了上面的数组,包括字母拼写游戏中字母表中的所有字母。
如果用户输入的字母值超出这些值,我不确定如何显示错误信息,例如。一个号码?任何帮助将不胜感激。
答案 0 :(得分:4)
您可以将其转换为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()
。
答案 1 :(得分:1)
你可以使用一个字符数组。这里给出了示例。然后,您可以使用indexof方法查看用户输入的值是否有效,如https://www.javatpoint.com/java-string-tochararray
答案 2 :(得分:1)
您可以使用: -
if (! ArrayUtils.contains( alpha, "[i-dont-exist]" ) ) {
try{
throw new Exception("Not Found !");
}catch(Exception e){}
}
答案 3 :(得分:1)
如果检查集合中元素是否存在的目的,则使用集合更合理,因为访问时间是不变的
所以相反
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
答案 4 :(得分:0)
如果您想坚持使用数组而不是其他数据结构,请使用此方法。
如果数组中存在用户输入,则创建一个返回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
}
在调用方法中,只需将用户输入传递给isValid
//write some codes here to receive user input.....
if(!isValid(input))
System.out.println("Oops, you have entered invalid input!");