[英]How to check if each element in a string array is an integer?
I'm attempting an error check that determines whether all the the elements of an array are integers, i've been stuck for a long time though. 我正在尝试进行错误检查,以确定数组的所有元素是否都是整数,不过我已经被卡住了很长时间了。 any ideas on how to get started would be helpful.
关于如何开始的任何想法都会有所帮助。
Scanner scan = new Scanner(System.in);
System.out.print("Please list at least one and up to 10 integers: ");
String integers = scan.nextLine();
String[] newArray = integers.split("");
Using the String you made with the scanner, loop over a space-delimited list and check that each element is an integer. 使用您使用扫描仪创建的字符串,循环使用空格分隔的列表,并检查每个元素是否为整数。 If they all pass, return true;
如果它们全部通过,则返回true;否则,返回true。 otherwise return false.
否则返回false。
Credit for the isInteger check goes to Determine if a String is an Integer in Java isInteger检查的功劳在于确定Java中字符串是否为整数
public static boolean containsAllIntegers(String integers){
String[] newArray = integers.split(" ");
//loop over the array; if any value isnt an integer return false.
for (String integer : newArray){
if (!isInteger(integer)){
return false;
}
}
return true;
}
public static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false;
}
// only got here if we didn't return false
return true;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.