0

I am trying to figure out how to make sure a String variable does not have a number as a string. I cannot Import anything.

I have tried

NameArray[i].equalsIgnoreCase("")) || Integer.parseInt(NameArray[i]) >= 48 && Integer.parseInt(NameArray[i]) < 58

but it did not work.

stinepike
  • 54,068
  • 14
  • 92
  • 112
Fifa
  • 21
  • 1
  • 1
    `"48".equals(NameArray[i].trim())` or some such, this way you avoid the issues of parsing a `String` which is not a number – MadProgrammer Apr 07 '17 at 03:27
  • Possible duplicate of http://stackoverflow.com/questions/237159/whats-the-best-way-to-check-to-see-if-a-string-represents-an-integer-in-java – Sumit Gulati Apr 07 '17 at 03:33
  • @Evelyn, as per my understanding you need to check if the string has any numeric value in it. Kindly check my answer and let me know if it helps :) – Devendra Lattu Apr 07 '17 at 03:38

3 Answers3

0

You can try converting string to number using Integer.parseInt(string). If it gives an Exception than it is not a number.

public boolean validNumber(String number) 
{
   try 
   {
     Integer.parseInt(number);
   } 
   catch (NumberFormatException e) 
   {
     return false;
   }
   return true;
}
Denis
  • 1,219
  • 1
  • 10
  • 15
0

In Java 8+, you might use an IntStream to generate a range ([48, 58]) and then check if that as a String is equal to your NameArray. Something like,

if (IntStream.rangeClosed(48, 58).anyMatch(x -> String.valueOf(x)
        .equals(NameArray[i]))) {

}

You mention that you want to make sure it doesn't contain a value - so perhaps you really want noneMatch like

if (IntStream.rangeClosed(48, 58).noneMatch(x -> String.valueOf(x)
        .equals(NameArray[i]))) {

}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

So, you need to check for a string which doesn't contain any numbers. Try using regex .*[0-9].* which will check for occurrence of any numerical character in your string.

    String regex = ".*[0-9].*";

    // Returns true
    System.out.println("1".matches(regex));
    System.out.println("100".matches(regex));
    System.out.println("Stack 12 Overflow".matches(regex));
    System.out.println("aa123bb".matches(regex));

    // Returns false
    System.out.println("Regex".matches(regex));
    System.out.println("Java".matches(regex));
Devendra Lattu
  • 2,732
  • 2
  • 18
  • 27