How to resolve NumberFormatException: Empty string?

大城市里の小女人 提交于 2021-01-28 02:53:47

问题


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

回答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
}



回答2:


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.



来源:https://stackoverflow.com/questions/14590263/how-to-resolve-numberformatexception-empty-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!