gpt4 book ai didi

java - 写入文件时出现 NoSuchElementException

转载 作者:行者123 更新时间:2023-12-01 15:05:36 25 4
gpt4 key购买 nike

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

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

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

关于java - 写入文件时出现 NoSuchElementException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12994152/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com