【发布时间】:2021-02-27 22:15:47
【问题描述】:
所以,我从文本文件中读取单词并将它们保存在 ArrayList 的 ArrayList 中。它应该完全按照文件中的内容打印单词。例如:
test1 test2 test3 test4 test5
test6 test7 test8
test9 test10
但它会打印:Actual output here 为什么它会有这样的行为以及如何解决它? 下面是阅读代码:
package com.company;
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.InputMismatchException;
import java.util.Scanner;
public class WordOrder {
public ArrayList<ArrayList<String>> LinesList;
public ArrayList<String> Words_per_line_list;
protected String FileName;
protected File file;
public WordOrder(){
LinesList = new ArrayList<>();
Words_per_line_list = new ArrayList<>();
}
public void wordReading() throws IOException, IndexOutOfBoundsException{
String word_to_be_read;
Scanner scan = new Scanner (System.in);
System.out.println ("Enter the name of the file");
FileName = scan.nextLine ();
file = new File(FileName);
BufferedReader in = new BufferedReader(new FileReader (FileName));
if(in.read () == -1){
throw new IOException ("File does not exist or cannot be accessed");
}
System.out.println ("Test");
int i =0, j = 0;
while(in.readLine() != null) {
LinesList.add(i, Words_per_line_list);
while ((in.read ()) != -1) {
word_to_be_read = in.readLine ();
Words_per_line_list.add(j, word_to_be_read);
System.out.println (LinesList.get (i).get (j));
j++;
}
i++;
}
}
任何帮助将不胜感激。
【问题讨论】:
-
什么是 LinesList 和 Words_per_line_list?你没有展示他们的定义/创作。
-
@pcoates 这是两个 ArrayList。 LinesList 是列表列表,而 Words_per_line_list 是字符串列表。它类似于:```LinesList
>```