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);
Share:
13,773
Shilpa Kancharla
Author by

Shilpa Kancharla

Updated on December 05, 2022

Comments

  • Shilpa Kancharla
    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 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.

    • deHaar
      deHaar almost 6 years
      Make sure the console.nextLine() is not an empty String, because the line Exception in thread "main" java.lang.NumberFormatException: For input string: "" says it is...
    • assylias
      assylias almost 6 years
      Note : assuming console is a Scanner, you could use console.nextInt().
    • vincrichaud
      vincrichaud almost 6 years
      Surround your call to parseInt() with a try-catch block catching this exception
    • soufrk
      soufrk almost 6 years
      Check if console.nextLine().trim().isEmpty() is true or not.
    • Jaroslaw Pawlak
      Jaroslaw Pawlak almost 6 years
      By the way, why the loop? This loop will never execute more than once...
    • Shilpa Kancharla
      Shilpa Kancharla almost 6 years
      @assylias I tried that, and it works. Thank you!
  • vincrichaud
    vincrichaud almost 6 years
    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.