线程“main”中的异常java.lang.NumberFormatException:empty String

时间:2017-12-06 19:09:53

标签: java exception

我的程序是从txt读取并打印它的某些部分。当我尝试设置Double d4时,它给出了一个错误,表示字符串是 空虽然不是。并且它也不是格式化的问题,因为当我删除该行时d1-5工作正常。我还打印了数据[5]并显示了来自txt的正确行。

import java.util.Scanner;
import java.io.*;
import java.text.DecimalFormat;
import java.util.ArrayList;


public class AAAAAA {
    public static void main (String[] args)throws IOException {

    final String fileName = "classQuizzes.txt";
//1)
    Scanner sc = new Scanner(new File(fileName));

    //declarations 
    String input;
    double total = 0.0;
    double num = 0;
    double count = 0;
    double average = 0;
    String lastName;
    String firstName;
    double minimum;
    double max;


//2) process rows   
    input = sc.nextLine();
    System.out.println(input); 
    while (sc.hasNextLine()) {

       String line = sc.nextLine();
       System.out.println(line);

    // split the line into pieces of data separated by the spaces
       String[] data = line.split(" ");

    // get the name from data[]
       System.out.println("d5 " +data[4]);
       firstName = data[0];
       lastName = data[1];
       Double d1 = Double.valueOf(data[2]);
       Double d2 = Double.valueOf(data[3]);
       Double d3 = Double.valueOf(data[4]);
       Double d4 = Double.valueOf(data[5]);
       Double d5 = Double.valueOf(data[6]);


    // do the same...
    System.out.println("data " + d3);
         total += d1 + d2 + d3  + d5;
         count++;

   //find average (decimal 2 points)
               System.out.println(count);
               average = total / count;
               System.out.println("Total = " + total);
               System.out.println("Average = " + average);

//3) class statistics




    //while
       }       
         System.out.println("Program created by");
     }
}

1 个答案:

答案 0 :(得分:1)

该行可能不是空的,但是当你在空格中分割它时,如果一行中有两个空格,你将在分割中得到空字符串。为防止这种情况,请更改

String[] data = line.split(" ");

String[] data = line.split(" *");

或者,或许更好,因为它将处理标签和其他空白区域:

String[] data = line.split("\\s*");

要自己跟踪这些类型的问题(并验证我是否已正确诊断出问题),您应该打印出拆分数组的每个元素,并验证数组长度是否符合预期。