2

When I run this program i get the error Exception in thread "main" java.lang.NumberFormatException: empty String. Is it possible to make this work by throwing the exception some how or must I use a try catch statement?

private double[] scores3 = new double[5]; 
Scanner keyboard = new Scanner(System.in);

public void enterData() 
{
   double score;
   double numberMin = 0;
   double numberMax = 100;



do{
    System.out.println("Enter the student's third test score");

      while (!keyboard.hasNextDouble()) {

      keyboard.next();
      }
       score3 = keyboard.nextDouble();


        }
         while  (score3 <= numberMin || score3 >= numberMax);
         double score3 = Double.parseDouble(keyboard.nextLine());
6
  • 4
    If you throw the exception, it still must be caught and handled somewhere. Just use a try/catch block. Commented Jan 29, 2013 at 19:01
  • 1
    I suggest you step through your code in your debugger as it isn't doing what you think it is doing. The Exception is symptom of a confused program, you are better off fixing the cause. Commented Jan 29, 2013 at 19:05
  • What is keyboard exactly? Commented Jan 29, 2013 at 19:08
  • 1
    I'm wondering why you parse keyboard.nextLine() and not score3? As far as I can tell, the error you got is there. Commented Jan 29, 2013 at 19:11
  • You can also use Apache commons StringUtils to check if a string is numeric prior to converting. Commented Jan 29, 2013 at 19:19

2 Answers 2

1

Before parsing a String to a Number.. compare the string with " " or use isEmpty() function to check if its a empty string or not !

Example:

if (myString.isEmpty()) {
    //Do Nothing
} else {
    //Code to perform calculations
}

or

if (!myString.isEmpty()) {
    //Code to perform calculations
}
Sign up to request clarification or add additional context in comments.

2 Comments

This would break for every non-numeric String that doesn't equal " ".
Should be myString.trım().isEmpty().
0

To your question of if you can throw the error elsewhere, you could do that by declaring

public void enterData() throws NumberFormatException

However I would recommend using a try catch block if you want to continue iterating over your while statements.

1 Comment

But if he throws it, he still must handle the thrown exception wherever he calls the method that is throwing it, and thus will need a try/catch block.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.