Вопрос

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

Это было полезно?

Решение

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;
}

Другие советы

This works for me. Simply to identify whether a String is a primitive or a number.

private boolean isPrimitive(String value){
        boolean status=true;
        if(value.length()<1)
            return false;
        for(int i = 0;i<value.length();i++){
            char c=value.charAt(i);
            if(Character.isDigit(c) || c=='.'){
                
            }else{
                status=false;
                break;
            }
        }
        return status;
    }

parseInt throws NumberFormatException if it cannot convert the String to an int. So you should surround the parseInt calls with a try catch block and catch that exception.

Basically, you have to decide to check if a given string is a valid integer or you simply assume a given string is a valid integer and an exception can occur at parsing.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top