0

I need to check if a string has only numbers in it so that I can parse it to an int. I am not allowed to use a try/catch statement. Nothing I have tried through here has worked thusfar, that's why it may seem like this has already been asked. Here's what I am trying:

    if (team1Part2.equals(Integer.parseInt(team1Part2))) {
        team1Score = Integer.parseInt(team1Part2);
    } else {
        team1Score = sc.nextInt();
    }

It's being read from a file, and if the first input isn't an integer, the next one is, but when ran, I get a mismatch on the else statement for some reason.

  • 3
    http://stackoverflow.com/questions/15111420/how-to-check-if-a-string-contains-only-digits-in-java – neo108 Oct 21 '16 at 00:17

1 Answers1

0
public class IsNumber {

    public static void main(String[] args) {
        String str = args[0];
        if (check(str)) {
            System.out.println("Input:" + str + " is a number");
        } else {
            System.out.println("Input:" + str + " is not a number");
        }
    }

    public static boolean check(String str) {
        for (char c : str.toCharArray()) {
            if (!Character.isDigit(c))
                return false;
        }
        return true;
    }
}
Nicolas Modrzyk
  • 13,961
  • 2
  • 36
  • 40