gpt4 book ai didi

java - 如何在Java中执行2个包含相同条件的While循环?

转载 作者:行者123 更新时间:2023-11-30 03:32:45 27 4
gpt4 key购买 nike

我正在使用 Java OpenCSV 库来读取和写入新文件。要求是在除最后一行之外的每一行末尾写入一个@符号。我成功地在每行后添加 @ 但最后一行不得包含 @。我的Java程序的一部分如下:

// A part of my Java code
String[] endOfLine;
String[] nextLine;
int endLine = 0;
int lineNumber = 0;

// To get how many line are in the input file
while ((endOfLine = reader.readNext()) != null) {
endLine++;
}

//For 8 lines endLine is 8 here - which is ok
//Now I want to pass this in next while loop - which is also ok

while ((nextLine = reader.readNext()) != null) {
lineNumber++;
channel_temp = nextLine[5];

if (lineNumber == endLine) {

//Build a new string with all our required data
String newdata = channel_temp;
writer.writeNext(newdata);
System.out.println(newdata);
}

else {

String newdata2 = channel_temp + "@";
writer.writeNext(newdata2);
System.out.println(newdata2);
}
}

System.out.println("lineNumber: " + lineNumber);
System.out.println("endLine: " + endLine);

程序显示输出为:

lineNumber: 0
endLine: 8

那么,为什么我的 while 循环 没有更新 lineNumber 值?我哪部分错了?

最佳答案

您需要再次初始化reader。在第一个循环之后,它位于文件的末尾。因此,在第二个循环中,reader.readNext()返回null,因此它永远不会进入第二个循环。

关于java - 如何在Java中执行2个包含相同条件的While循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28641182/

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