1

So this is how I have my code (of course, not finished because I don't want to do any other work until I can figure out why I'm getting the error). It compiles no problem but when I try to run it I get a java.lang.NumberFormatException for my first line, not really sure why?

 if (Integer.parseInt(subtotalTextField.getText()) <= 200)
 {
    discountTextField.setText("2");
 }
    else
 {
 }
Bostone
  • 36,858
  • 39
  • 167
  • 227

4 Answers4

4

Because subtotalTextField.getText() returns something that is not parsable to int, in exception message it should show what was the value that was passed to parseInt()

jmj
  • 237,923
  • 42
  • 401
  • 438
0

What's returned is not a String perhaps? Don't chain it, check for null and do

Object val = subtotalTextField.getText();
if (val != null)
    String txt = val.toString();
Bostone
  • 36,858
  • 39
  • 167
  • 227
  • It must be a string otherwise there would be a compile-time error (and `getText` usually means string). `NumberFormatException`s usually indicate that a string can't be parsed as an int (or other numeric type). – arshajii Dec 01 '12 at 02:17
  • It is a string, but not an integer representation – AlexWien Dec 01 '12 at 02:17
  • Not in Android for example - there it will return Spannable – Bostone Dec 01 '12 at 04:46
0

As stated, the text entered in the textfield can't be parsed to an Integer. This means that your textfield contains characters i.e. "2s" .

if you want to avoid this error everytime an user enters a non-valid Integer, surround it with a try-catch clause.

try{
// Try to parse to Integer

}catch(NumberFormatException e) {
// Thing to do when a user enters non-valid Integer
}
chribsen
  • 6,232
  • 4
  • 26
  • 24
0

Possible value for subtotalTextField.getText() that I can think about it

 subtotalTextField.getText() = null; // or

 subtotalTextField.getText() = "";  // or

 subtotalTextField.getText() = "Any non passable String"; // a ,b c .. 1a ,2a ... etc

If you could make sure user is entered value is valid number by any validation. No problem start with your logic.

someone
  • 6,577
  • 7
  • 37
  • 60