1

假设文本文件包含:

He is a boy .
She is sick .
Ali is playing .
We are eating .
The dog is barking .
He and his brother are running .

如何将所有句子按格式放入数组列表中:

He is
is a 
a boy
boy .
She is
is sick
sick .

等等。

我使用数组列表来避免继续阅读文本文件来执行某些任务是否可能?或者我需要使用矢量来做到这一点?

4

3 回答 3

6

这应该可以。我没有测试它。这只是一行代码,您需要一些东西来扫描您的输入并使用每一行;

String line = "He is a boy .";
String[] arr = line.split(" ");
ArrayList<String> newLines = ArrayList<String>();
for (int i = 1; i < arr.length; i++){
  newLines.add(arr[i-1]+" "+arr[i]);
}
于 2012-07-04T03:59:59.933 回答
0

除了 Arthur 所说的之外,您还可以例如使用 The Scanner类从文件中读取输入:

Scanner fileScanner = null;
try {
    fileScanner = new Scanner(new File("yourtextfile.txt"));
} catch (FileNotFoundException e) {
    e.printStackTrace();  
}
while (fileScanner.hasNextLine()) {
    // Some additional code for storing the output to an array around here? :]
    System.out.println(fileScanner.nextLine());
}
于 2012-07-04T06:39:17.907 回答
-2

同样,如果您不想从文件中读取,而是从用户输入中读取,则可以使用它

ArrayList<String> uInput = new ArrayList<String>(Arrays.asList(scan.nextLine().split("\\s+")));
于 2013-01-03T14:23:40.053 回答