0

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("");
Kevin Grant
  • 1
  • 1
  • 1
  • 2

1 Answers1

0

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;
}
Community
  • 1
  • 1
astennent
  • 36
  • 4
  • This is not good...catching exceptions for every item in the array that is not a number is bad. Use int.TryParse instead – Afra Jan 27 '16 at 08:40