簡體   English   中英

NoSuchElementException寫入文件時

[英]NoSuchElementException When writng to file

我正在編寫一個程序,該程序從文件中讀取字符串和整數,然后復制數據並寫入另一個文件。 數據條目應以空格分隔。

我的輸入和輸出應遵循以下格式,前兩組數字是字符串,而其他兩組是整數:

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

我懷疑掃描儀的行數據已用完-可能是因為其中的值少於6。 為了避免該錯誤,您應該執行以下操作:

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

您的掃描程序正在嘗試讀入不存在或類型錯誤的令牌。 我本人將String分割為一行,使用“”作為分隔符,然后處理返回的數組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM