我正在尝试编写一个层次块,将元素放入一个 ArrayList 中,所有这些都与一个更大的 ArrayList 分开。该块所做的是获取现有的文本输入,并将每一行文本添加到 ArrayList 的元素中。然后将每一行创建为字符串的 ArrayList,每个字符串都是该行上的一个单词(我在空格 (" ") 处使用字符串拆分来执行此操作)。
我的问题是在尝试创建它时我需要使用 Arrays.asList (因为字符串拆分返回一个列表)
Action Syllables = new AbstractAction("Syllables") {
public void actionPerformed(ActionEvent e) {
ArrayList<String> text = LinetoList(area);
//"text" is a String ArrayList of every "line" in a piece of text
//LinetoList is a method that returns an ArrayList based on each new line
ArrayList<ArrayList> words = new ArrayList();
for (int i = 0; i < text.size(); i++) {
ArrayList sentence = (ArrayList) Arrays.asList(text.get(i).split(" "));
/*Sentence is currently a list, however, changing the type to an Array
* or Arraylist Changes nothing */
words.add(sentence);
}
for (int k = 0; k < words.size(); k++) {
for (int i= 0; i < words.get(k).size(); i ++) {
System.out.println(words.get(k).get(i));
}
}
}
};
这是我返回错误的原始方法。我已经稍微调整了一下,它不再返回错误但是,没有返回任何东西。
Action Syllables = new AbstractAction("Syllables") {
public void actionPerformed(ActionEvent e) {
ArrayList<String> text = LinetoList(area);
//"text" is a String ArrayList of every "line" in a piece of text
//LinetoList is a method that returns an ArrayList based on each new "line"
ArrayList<ArrayList> words = new ArrayList();
for (int i = 0; i < text.size(); i++) {
ArrayList <String> sentences = new ArrayList();
String sentence[] = text.get(i).split(" ");
sentence = sentences.toArray(sentence);
/*Sentence is currently a list, however, changing the type to an Array
* or Arraylist Changes nothing */
words.add(sentences);
}
if (words.size() == 0)
{System.out.println("Theres nothing here"); }
else {
for (int k = 0; k < words.size(); k++) {
for (int i= 0; i < words.get(k).size(); i ++) {
System.out.println(words.get(k).get(i));}
}
}
}
};
非常感谢有关如何处理解决方案的任何反馈或想法。
编辑:有些人要求使用 LinetoList 功能。大多数程序使用字符串的 ArrayLists,这就是为什么它在这里被大量使用的原因。
private static ArrayList<String> LinetoList(JTextArea textArea) {
String s[] = textArea.getText().split("\\r?\\n");
ArrayList<String>arrList = new ArrayList<>(Arrays.asList(s)) ;
return arrList;
}