How to check if a string is a valid integer?

java, variable-assignment

Solution

You can't do `if (int i = 0)`, because assignment returns the assigned value (in this case `0`) and `if` expects an expression that evaluates either to `true`, or `false`.

On the other hand, if your goal is to check, whether `jTextField.getText()` returns a numeric value, that can be parsed to `int`, you can attempt to do the parsing and if the value is not suitable, `NumberFormatException` will be raised, to let you know.

try {
    op1 = Integer.parseInt(jTextField1.getText());
} catch (NumberFormatException e) {
    System.out.println("Wrong number");
    op1 = 0;
}

Problem

I have: ``` op1 = Integer.parseInt(jTextField1.getText()); op2 = Integer.parseInt(jTextField2.getText()); ``` However, I want to check first whether the text fields' values can be assigned to integer variables. How do I do that? I've been going through this for a long time, so, if this was already asked here, forgive me

Original source

Related problems