Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a string is a valid integer? [duplicate]

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

like image 791
Dannyl Avatar asked Feb 15 '14 21:02

Dannyl


People also ask

How do you check if a string is Parsable to int?

You can use Integer. parseInt() or Integer. valueOf() to get the integer from the string, and catch the exception if it is not a parsable int.

How do you check if a string can be a double?

Therefore, to know whether a particular string is parse-able to double or not, pass it to the parseDouble method and wrap this line with try-catch block. If an exception occurs this indicates that the given String is not pars able to double.


3 Answers

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;
}
like image 149
Warlord Avatar answered Oct 14 '22 17:10

Warlord


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;
    }
like image 30
Niroshan Abeywickrama Avatar answered Oct 14 '22 17:10

Niroshan Abeywickrama


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.

like image 45
xp500 Avatar answered Oct 14 '22 16:10

xp500