java中关于从输入文件读取的以下方法的问题

时间:2014-08-02 00:17:17

标签: java adt

大家好,所以当我尝试运行程序时,我不断收到以下错误。

Exception in thread "main" java.lang.NumberFormatException: For input string: ""
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:592)
    at java.lang.Integer.parseInt(Integer.java:615)
    at Simulation.getJob(Simulation.java:12)
    at Simulation.main(Simulation.java:58)

我正在使用的代码片段如下:

//all of this is under main.
    m = Integer.parseInt( in.nextLine() );
    //make sure the file has stuff in it
    while(in.hasNext()){
        in.useDelimiter("\n");
        //Create an array of type job to keep track of our number of jobs.
        Job[] jobs = new Job[m];



        for(int i = 1; i < m; i++){
         jobs[i] = getJob(in);
         System.out.println(jobs[i]);
        }
    }

//getJob function is here:
public static Job getJob(Scanner in){
    String[] s = in.nextLine().split(" ");
    int a = Integer.parseInt(s[0]);
    int d = Integer.parseInt(s[1]);
    return new Job(a,d);
    }

来自in文件的数据如下所示 3 2 2 3 4 5 6

1 个答案:

答案 0 :(得分:1)

问题是您的代码与输入格式不匹配:当嵌套的for循环结束时,外部while循环会将您带回到读取代码的开头,并尝试阅读另一组m项。

要解决此问题,只需删除外部循环:

in.useDelimiter("\n");
//Create an array of type job to keep track of our number of jobs.
Job[] jobs = new Job[m];
for(int i = 0; i < m; i++){
    jobs[i] = getJob(in);
    System.out.println(jobs[i]);
}

请注意,循环索引i需要从零开始,而不是1,因为Java数组是从零开始的。