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.

1

1 Answer 1

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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.