Search code examples
javanumberformatexception

How do I fix the error of NumberFormatException everytime I run the program?


I have to create a love calculator object for my computer science class. However, every time I compile and run the program I keep ending up with the error:

java.lang.NumberFormatException:

For input string: "70.78%" (in sun.misc.FloatingDecimal)

My code for the method:

public double calculate()
{
    double value1;
    double value2;
    double sqrt1;
    double sqrt2;
    double relationship;
    sqrt1 = Math.sqrt(name1.length());
    sqrt2 = Math.sqrt(name2.length());
    value1 = (Math.pow(name1.length(), 3)/(Math.random()+0.1))* sqrt1;
    value2 = (Math.pow(name2.length(), 3)/(Math.random()+0.1))* sqrt2;

    if(value1 > value2)
    {
        relationship = value2 / value1;
    }
    else
    {
        relationship = value1 / value2;
    }
    NumberFormat nf = NumberFormat.getPercentInstance();
    nf.setMinimumFractionDigits(2);
    return Double.parseDouble(nf.format(relationship));
}

I attempted to convert it to a float. I tried to separate it by declaring and initializing another double variable and returning that instead but they didn't work. I looked up solutions and most said to use a try and catch but I don't understand how that would work (since I just began the class and am a beginner).

How would I use a try and catch for this situation?


Solution

  • NumberFormat is meant to create a human readable string. 70.78% isn't a number. 70.78 is, but with the percent sign, it's a string. It seems like what you're trying to do is use the number formatting functionality to round the number. This question has some suggestions for how to properly round a number and keep it as a number.

    To answer your other question, the proper way to use a try/catch would be like this:

     double result;
     try{
       result = Double.parseDouble(nf.format(relationship));
     }catch(NumberFormatException e){
       e.printStackTrace();
       result = 0.0;
     }
     return result;
    

    But the only thing that will do is cause your program to not crash and you'll always get 0.0 returned from the calculate() method. Instead you need to fix the source of the exception.