0

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

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

The above will work as is, it's been in Java since 1.5 (I think?). If you really insists on the old style, add the line "String element = a[i];" directly after the loop declaration. However, I really think you should be using the improved for loop.
2

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

2 Comments

This will work Quoi, but the "catch" for program flow is something I don't like. I agree that there is no other way for the above. Functional java with "Either" as a return type would be a nice alternative.
@JacoVanNiekerk - Even in that case Pattern matching would be alternative.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.