所以这基本上就是我希望我的代码所说的内容,以避免在用户选择“Tea”而不是使用相应的整数时出现编译错误。
if(appSelection < 1 || appSelection > appetizersArray.length || appSelection != int)
前两个条件显然是为了捕获超出范围的数据,但我正在寻找一种方法来指定输入需要是 int。
如果唯一的选择是try catch
,就这么说,但我希望有一个更优雅的解决方案。
最佳答案
您可以使用正则表达式。小写的\\d
匹配数字,加一个加号表示连续。所以,
String regex = "\\d+";
String[] arr = { "Tea", "123" };
for (String str : arr) {
if (str.matches(regex)) {
System.out.printf("%s is all digits%n", str);
} else {
System.out.printf("%s is NOT all digits%n", str);
}
}
输出为
Tea is NOT all digits
123 is all digits
关于java - 有没有办法通过说 "variable != int"来验证数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26894326/