java - 如何解决 NumberFormatException : Empty string?

标签 java validation numberformatexception

当我运行这个程序时,我在线程“main”java.lang.NumberFormatException 中收到错误异常:空字符串。是否可以通过某种方式或必须使用 try catch 语句抛出异常来完成这项工作?

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

最佳答案

在将字符串解析为数字之前.. 将字符串与 ""进行比较或使用 isEmpty() 函数来检查它是否为空字符串!

例子:

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

if (!myString.isEmpty()) {
    //Code to perform calculations
}

关于java - 如何解决 NumberFormatException : Empty string?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14590263/

相关文章:

java - 不确定我在这里做错了什么( boolean 标志)

java - 浏览器和 postman 返回结果,但 Resttemplate 由于 %26 返回 0 个结果

validation - 验证maven属性值

java - 尝试从控制台输入读取日期时出现 NumberFormatException

java - 当我打开相机时应用程序崩溃

java - 当我尝试在 postman 中返回消息时出现额外的空值

c++ - 只允许在程序中使用选择的字母(字符串)?

excel - 通过数据验证防止出现空白单元格

java.lang.NumberFormatException : Invalid int: "1"

Java MySQL 连接NumberFormat 异常?