问题
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