user1580945
user1580945

Reputation: 91

Identify the Element in String array in java

I want to identify the elements in letters and elements in numbers in String array.Is there any other way to do it?

String a[]={"aaaa","111111","bbbbbb"};





for(int i=0;i<a.length;i++)
{
post your code for this FOR LOOP
}

Upvotes: 0

Views: 138

Answers (2)

Jaco Van Niekerk
Jaco Van Niekerk

Reputation: 4182

They say that you have a problem... so you choose regular expressions to solve it, now you have two problems. :-)

However, if speed is not that much of an issue, you could attempt it, assuming you have good unit tests in place. Something along the lines of:

public static void testRegularExpressionForElement() {
    String[] a = new String[] {"test1", "13", "blah", "1234.44"};

    Pattern pattern = Pattern.compile("[-+]?[0-9]*\\.?[0-9]+");
    for (String element : a) {
        if (pattern.matcher(element).matches()) {
            System.out.println(element + " is a number");
        } else {
            System.out.println(element + " is not a number");
        }
    }
}

What's nice about the above, is that you can adapt the expression to match exactly what you want.

Another approach would be is to use Integer.parseInt() and catching the exceptions, but this is bad programming as you're using exceptions for logic.

Upvotes: 3

Subhrajyoti Majumder
Subhrajyoti Majumder

Reputation: 41200

Traverse the array and write a function to check isNumeric or not.

for (a1 : a){
   boolean isNumbr= isNumeric(a1);
}

...

public static boolean isNumeric(String str)  
{  
  try  
  {  
    double d = Double.parseDouble(str);  
  }  
  catch(NumberFormatException nfe)  
  {  
    return false;  
  }  
  return true;  
}

Upvotes: 2

Related Questions