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

2 Answers2

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
0

//we can use regex as well like below if anyone is still searching for the answer

public class testclass3 {

public static boolean findStringValues(String o, Integer len) {
    
    if (((o.replaceAll("[0-9]", "")).length())==len) {
        return true;
    }
    
    return false;
}

public static void main(String[] args) {
    String[] strValues = {"ABX","XYZ","1234","PUNE30"};
    int count=0;
    for(int i=0;i<strValues.length;i++) {
         if(!(findStringValues(strValues[i],strValues[i].length()))) {
             count = count +1;
         }
    }System.out.println(count);
    
}

}

//OR if your array is an object array with Integer and String values the below implementation should work

public void findPureStringCount() {
    int count=0;
    Object[] arrStr = {123,"abc","abc123"};
    for(Object str : arrStr) {
        if (str instanceof String) {
            count = count+1;
        }
    }
    System.out.println(count);
}