【问题标题】:NoSuchElementException When writng to fileNoSuchElementException 写入文件时
【发布时间】:2012-10-11 05:49:43
【问题描述】:

我正在编写一个程序,它从文件中读取字符串和整数,然后复制数据并写入另一个文件。数据条目应以空格分隔。

我的输入和输出应该遵循以下格式,前两组数字是字符串,其他是整数:

123123 242323 09 08 06 44

当我运行我的代码时,我在线程“main”java.util.NoSuchElementException 中得到异常,我不知道为什么

import java.util.Scanner;
import java.io.*;

public class Billing {



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

        //define the variables


        String callingnumber;
        String callednumber;
        String line;
        int startinghour;
        int startingminute;
        int endinghour;
        int endingminute;


        //open input and output files
        FileReader freader = new FileReader("BillingData.txt");
        BufferedReader inFile = new BufferedReader(freader);


        FileWriter fwriter = new FileWriter("BillingOutput.txt");
        PrintWriter outFile = new PrintWriter (fwriter);

        // set space between the numbers
         line=inFile.readLine();
         while(line!=null)
         {
             //creat a scanner to use space between the numbers
             Scanner space = new Scanner(line).useDelimiter(" ");


             callingnumber=space.next();
             callednumber=space.next();
             startinghour=space.nextInt();
             startingminute=space.nextInt();
             endinghour=space.nextInt();
             endingminute=space.nextInt();



            // writing data to file
             outFile.printf("%s %s %d %d %d %d", callingnumber, callednumber,startinghour, startingminute, endinghour, endingminute);

             line=inFile.readLine();



         }//end while

         //close the files
         inFile.close();
         outFile.close();


    }//end of mine


}//end of class

【问题讨论】:

  • 您的输入文件中有空白字段?

标签: java exception file-io exception-handling textinput


【解决方案1】:

我怀疑扫描仪已用完该行中的数据 - 可能是因为其中的值少于 6 个。为避免该错误,您应该执行以下操作:

if (space.hasNextInt()) {
    startingHour = space.nextInt();
}

【讨论】:

    【解决方案2】:

    您的扫描仪正在尝试读取不存在或类型错误的令牌。我自己,我会使用“”作为分隔符分割字符串,然后处理返回的数组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-27
      • 1970-01-01
      • 2016-01-30
      • 2021-09-17
      相关资源
      最近更新 更多