NumberFormatException: For input string: ""?
13,773
Sometimes it simply means that you're passing an empty string into Integer.parseInt()
:
String a = "";
int i = Integer.parseInt(a);
Author by
Shilpa Kancharla
Updated on December 05, 2022Comments
-
Shilpa Kancharla over 1 year
Code
int weight = 0; do { System.out.print("Weight (lb): "); weight = Integer.parseInt(console.nextLine()); if (weight <= 0) { throw new IllegalArgumentException("Invalid weight."); } } while (weight <= 0);
Traceback
Weight (lb): Exception in thread "main" java.lang.NumberFormatException: For input string: "" at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.base/java.lang.Integer.parseInt(Integer.java:662) at java.base/java.lang.Integer.parseInt(Integer.java:770) at HealthPlan.main(HealthPlan.java:46)
When I run my program, I get this exception. How do I handle it?
I want to input an integer as a
weight
value. I also have to use an integer value forheight
, but my program asks for input that areboolean
s andcharacter
s as well.Someone suggested that I should use
Integer.parseInt
.If I need to post more code, I'd be happy to do so.
-
deHaar almost 6 yearsMake sure the
console.nextLine()
is not an emptyString
, because the lineException in thread "main" java.lang.NumberFormatException: For input string: ""
says it is... -
assylias almost 6 yearsNote : assuming
console
is aScanner
, you could useconsole.nextInt()
. -
vincrichaud almost 6 yearsSurround your call to
parseInt()
with a try-catch block catching this exception -
soufrk almost 6 yearsCheck if
console.nextLine().trim().isEmpty()
is true or not. -
Jaroslaw Pawlak almost 6 yearsBy the way, why the loop? This loop will never execute more than once...
-
Shilpa Kancharla almost 6 years@assylias I tried that, and it works. Thank you!
-
-
vincrichaud almost 6 yearsYou can cast String to Integer, it's just that you String need to be well formatted. For example
Integer.parseInt("124")
is totally correct.