Nick
Nick

Reputation: 71

How to determine whether a string contains an integer?

Say you have a string that you want to test to make sure that it contains an integer before you proceed with other the rest of the code. What would you use, in java, to find out whether or not it is an integer?

Upvotes: 6

Views: 65964

Answers (12)

Freddie
Freddie

Reputation: 1707

Use the method Integer.parseInt() at http://docs.oracle.com/javase/10/docs/api/java/lang/Integer.html

Upvotes: -1

user489041
user489041

Reputation: 28304

String s = "abc123";
for(char c : s.toCharArray()) {
    if(Character.isDigit(c)) {
        return true;
    }
}
return false;

Upvotes: 3

fty4
fty4

Reputation: 567

That should work:

public static boolean isInteger(String p_str)
{
    if (p_str == null)
        return false;
    else
        return p_str.matches("^\\d*$");
}

Upvotes: 0

CoolBeans
CoolBeans

Reputation: 20800

You can use apache StringUtils.isNumeric .

Upvotes: 1

Ryan Heitner
Ryan Heitner

Reputation: 13632

You could always use Googles Guava

String text = "13567";
CharMatcher charMatcher = CharMatcher.DIGIT;
int output = charMatcher.countIn(text);

Upvotes: 0

kirchhoff
kirchhoff

Reputation: 216

I use the method matches() from the String class:

    Scanner input = new Scanner(System.in)
    String lectura;
    int number;
    lectura = input.next();
    if(lectura.matches("[0-3]")){
         number = lectura;
    }

This way you can also validate that the range of the numbers is correct.

Upvotes: 1

Jon
Jon

Reputation: 1

int number = 0;
try { 
   number = Integer.parseInt(string); 
}
catch(NumberFormatException e) {}

Upvotes: -1

Pau
Pau

Reputation: 803

You might also want to have a look at java.util.Scanner

Example:

new Scanner("456").nextInt

Upvotes: 0

Andreas Dolk
Andreas Dolk

Reputation: 114777

If you just want to test, if a String contains an integer value only, write a method like this:

public boolean isInteger(String s) {
  boolean result = false;
  try {
    Integer.parseInt("-1234");
    result = true;
  } catch (NumberFormatException nfe) {
    // no need to handle the exception
  }
  return result;
}

parseInt will return the int value (-1234 in this example) or throw an exception.

Upvotes: -1

AlexR
AlexR

Reputation: 115328

  1. User regular expression:

    Pattern.compile("^\\s*\\d+\\s*$").matcher(myString).find();

  2. Just wrap Integer.parse() by try/catch(NumberFormatException)

Upvotes: 0

dimitrisli
dimitrisli

Reputation: 21391

You can check whether the following is true: "yourStringHere".matches("\\d+")

Upvotes: 8

Jonathon Bolster
Jonathon Bolster

Reputation: 15961

If you want to make sure that it is only an integer and convert it to one, I would use parseInt in a try/catch. However, if you want to check if the string contains a number then you would be better to use the String.matches with Regular Expressions: stringVariable.matches("\\d")

Upvotes: 15

Related Questions