Reputation: 107
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 for height
, but my program asks for input that are boolean
s and character
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.
Upvotes: 2
Views: 22942
Reputation: 21
Sometimes it simply means that you're passing an empty string into Integer.parseInt()
:
String a = "";
int i = Integer.parseInt(a);
Upvotes: 2
Reputation: 109547
As I did not see a solution given:
int weight = 0;
do {
System.out.print("Weight (lb): ");
String line = console.nextLine();
if (!line.matches("-?\\d+")) { // Matches 1 or more digits
weight = -1;
System.out.println("Invalid weight, not a number: " + line);
} else {
weight = Integer.parseInt(line);
System.out.println("Invalid weight, not positive: " + weight);
}
} while (weight <= 0);
Integer.parseInt(String)
has to be given a valid int.
Also possible is:
try {
weight = Integer.parseInt(line);
} catch (NumberFormatException e) {
weight = -1;
}
This would also help with overflow, entering 9999999999999999.
Upvotes: 0
Reputation: 5
You can only cast String into an Integer in this case.
Integer.parseInt("345")
but not in this case
Integer.parseInt("abc")
This line is giving an exception
Integer.parseInt(console.nextLine());
Instead, Use this
Integer.parseInt(console.nextInt());
Upvotes: 0