简体   繁体   English

ArrayList中的一行没有打印出来

[英]One line in ArrayList isn't printed out

My code has to read 50 lines of input and output them in reverse order, then other 50 lines, so output starts from 50th line, goes to the 1st one, then it start from 100th line to 50th I got it to work. 我的代码必须读取50行输入并以相反的顺序输出它们,然后再输出其他50行,因此输出从第50行开始,转到第1行,然后从第100行开始到第50行,我开始工作了。 But the only thing, that 51 line isn't printed, I can't get what's going wrong. 但唯一的事情是,这51行没有打印出来,我无法弄清问题所在。

public static void doIt(BufferedReader r, PrintWriter w) throws IOException {
    String newString;
    LinkedList<String> list = new LinkedList<String>();
    int i = 0;
    while ((newString = r.readLine()) != null) {
        if (i < 50) {
            i++;
            list.addFirst(newString);
        } else {
            for (String s : list)
                w.println(s);
            list.clear();
            i = 0;
        }
    }

    for (String s : list)
        w.println(s);

}

Change your code as follow: 更改您的代码,如下所示:

 i++; 
list.addFirst(newString); 

to

list.addFirst(newString); 
 i++; 

Because the way you are adding newString to list will skip one count 因为您将newString添加到列表的方式将跳过一个计数

Update: 更新:

Sorry but I have to fix my answer rather than deleting this. 抱歉,我必须解决我的问题,而不是删除它。 I checked it twice and as per the right answer add this line :-) 我检查了两次,并根据正确的答案添加了这一行:-)

list.addFirst(newString);

You are discarding the line you read when i == 50, here is a fix that makes it work. 当i == 50时,您将丢弃所读取的行,这是一个使其起作用的修复程序。

public static void doIt(BufferedReader r, PrintWriter w) throws IOException {

String newString;
LinkedList<String> list = new LinkedList<String>();
int i = 0;
while ((newString = r.readLine()) != null) {
    if (i < 50) {
        i++;
        list.addFirst(newString);
    } else {
        for (String s : list)
            w.println(s);
        list.clear();
        list.addFirst(newString); // <---- add this line and you should be fine
        i = 0;
    }
}

for (String s : list)
    w.println(s);

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM