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 use Integer. parseInt() or Integer. valueOf() to get the integer from the string, and catch the exception if it is not a parsable int.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With