Issue
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("");
Solution
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; otherwise return false.
Credit for the isInteger check goes to Determine if a String is an Integer in 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;
}
Answered By - astennent Answer Checked By - Mary Flores (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.