【发布时间】:2017-09-29 08:07:35
【问题描述】:
我正在为学校做 Java 作业。任务是处理2个文件读取第一个,用第二个对第一个进行调整,最后输出到一个新文件中。
Scanner inputRecords = new Scanner(new File("Records.txt"));
Scanner inputTransactions = new Scanner(new File("Transactions.txt"));
BufferedWriter outputFile = (new BufferedWriter(new FileWriter("NewRecords.txt", true)));
char code; // transaction code
String lineTran = "";
String lineRecord = "";
String midS = "";
String tidS = "";
int tid = 0, mid= 0;
for (int x = 0; x < 6; x++)
{
lineTran = inputTransactions.nextLine();
code = lineTran.charAt(0);
System.out.println(code);
tidS = lineTran.substring(2,11);
tid = Integer.parseInt(tidS);
lineRecord = inputRecords.nextLine();
midS = lineRecord.substring(0,9);
mid = Integer.parseInt(midS);
if (mid < tid) // add a new record lineTran.substring(2,lineTran.length()
{
outputFile.write(lineRecord);
outputFile.newLine();
lineRecord = inputRecords.nextLine();
}
else if (mid == tid )
{
if (code == 'C') //change record
{
outputFile.write(lineTran.substring(2,lineTran.length()));
outputFile.newLine();
lineTran = inputTransactions.nextLine();
}
else if (code == 'D') //delete record
{
lineTran = inputTransactions.nextLine();
lineRecord = inputRecords.nextLine();
}
else // add error
{
System.out.println(lineRecord + " Already Exists...add error");
lineTran = inputTransactions.nextLine();
}
}
else
{
if (code == 'A') // add record
{
outputFile.write(lineTran.substring(2,lineTran.length()));
outputFile.newLine();
lineTran = inputTransactions.nextLine();
}
else if (code == 'C') // change error
{
System.out.println(lineRecord + " Record already exist...Change Error");
lineTran = inputTransactions.nextLine();
}
else // delete error
{
System.out.println(lineRecord + " Record does not exist...delete error");
lineTran = inputTransactions.nextLine();
}
}
请注意: Records.txt 有 10 行信息(例如:######### lastname firstname 职业) Transactions.txt 有 6 行信息(例如:'A,D,or C' ######### lastname firstname 职业)
我遇到的问题是无论我运行哪种类型的循环,我都会到达 2 个死胡同之一。 1)在上面的for循环的情况下
D 一种 C 一种 C 386326383 Slim Kan personalTrainer 未发现任何更改...更改错误
线程“主”java.lang.StringIndexOutOfBoundsException 中的异常:字符串索引超出范围:0 在 java.lang.String.charAt(未知来源) 在 fileHandling.main(fileHandling.java:26) 是结果,没有写入文件。
2) 如果我通过 x
我尝试了“do while”和“while”循环,但结果相似。有什么建议吗?
【问题讨论】:
-
"StringIndexOutOfBoundsException: String index out of range: 0"有什么不清楚的地方?您的文件中有空行,您的代码无法处理。
-
不,我确保文件是干净的并且设置正确,并且我确信在这两种情况下循环都没有到达一个额外的行。
标签: java loops file-handling