Java ArrayList中的一行不是';没有打印出来
我的代码必须读取50行输入并以相反的顺序输出,然后是其他50行,所以输出从第50行开始,到第1行,然后从第100行开始到第50行,我让它工作。但唯一的问题是,51行没有打印出来,我不知道出了什么问题Java ArrayList中的一行不是';没有打印出来,java,linked-list,Java,Linked List,我的代码必须读取50行输入并以相反的顺序输出,然后是其他50行,所以输出从第50行开始,到第1行,然后从第100行开始到第50行,我让它工作。但唯一的问题是,51行没有打印出来,我不知道出了什么问题 public static void doIt(BufferedReader r, PrintWriter w) throws IOException { String newString; LinkedList<String> list = new LinkedList
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);
}
publicstaticvoiddoit(BufferedReader r,PrintWriter w)抛出IOException{
字符串新闻字符串;
LinkedList=新建LinkedList();
int i=0;
while((newString=r.readLine())!=null){
如果(i<50){
i++;
list.addFirst(新闻字符串);
}否则{
用于(字符串s:列表)
w、 println(s);
list.clear();
i=0;
}
}
用于(字符串s:列表)
w、 println(s);
}
更改代码如下:
i++;
list.addFirst(newString);
到
因为您将新闻字符串添加到列表的方式将跳过一次计数
更新:
对不起,我必须修正我的答案,而不是删除这个。我检查了两次,根据正确的答案加上这一行:-)
当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);
}
publicstaticvoiddoit(BufferedReader r,PrintWriter w)抛出IOException{
字符串新闻字符串;
LinkedList=新建LinkedList();
int i=0;
while((newString=r.readLine())!=null){
如果(i<50){
i++;
list.addFirst(新闻字符串);
}否则{
用于(字符串s:列表)
w、 println(s);
list.clear();
list.addFirst(新闻字符串);//是的,他是递增的,然后才加。但是他必须用另一种方法对我来说,没有区别,我会等:)因此他没有得到第一个元素,应该是第51个元素。@Nabin嘿,谢谢你,但是它不起作用,而且我不是索引,它只是一个整数,用来保存strings@user2847624对我知道我不是索引。
list.addFirst(newString);
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);
}