2

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 booleans and characters as well.

Someone suggested that I should use Integer.parseInt.

If I need to post more code, I'd be happy to do so.

Mikhail Kholodkov
  • 23,642
  • 17
  • 61
  • 78
Shilpa Kancharla
  • 107
  • 2
  • 2
  • 8

3 Answers3

2

Sometimes it simply means that you're passing an empty string into Integer.parseInt():

String a = "";
int i = Integer.parseInt(a);
fcdt
  • 2,371
  • 5
  • 14
  • 26
yyj
  • 21
  • 3
0

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());

  • You can cast String to Integer, it's just that you String need to be well formatted. For example `Integer.parseInt("124")` is totally correct. – vincrichaud Jun 26 '18 at 12:54
0

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.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138