简体   繁体   中英

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; 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM