简体   繁体   中英

Adding Input to JTextArea to an ArrayList of ArrayLists

My objective is to add the text from a JTextArea into an ArrayList of ArrayLists, such that each line of text inputted is saved as an ArrayList, with the words of that particular line saved as elements within the ArrayList of that line. I have an idea of how to store each line of the inputted text as an element within an ArrayList, but not how to have an ArrayList of ArrayLists. Could anyone point me in the right direction here? I would like to create a 2D ArrayList and was thinking something like this:

ArrayList[][] poem = new ArrayList[][];

This is what I was thinking for making an ArrayList containing each line as an element, but I would like to have each of the lines as a seperate ArrayList containing their respective words as elements:

JTextArea txArea = new JTextArea();
String txt = txArea.getText();
String [] arrayOfLines = txt.split("\n");
ArrayList<String> linesAsAL = new ArrayList<String>();
for(String line: arrayOfLines){
  linesAsAL.add(line);
}

In sum, I am trying to make a 2D ArrayList, where each word inputted into a JTextArea would be added into its own cell within that 2D ArrayList.

Your question doesn't have to be JTextArea -specific, so my answer won't (I'm assuming you know how to get a string from a JTextArea . Hint: http://docs.oracle.com/javase/7/docs/api/javax/swing/JTextArea.html ).

Here's a method to transform a String into an ArrayList<ArrayList<String>> :

public static List<List<String>> linesToLinesAndWords(String lines) {
    List<List<String>> wordlists = new ArrayList<>();
    List<String> lineList = Arrays.asList(lines.split("\n"));
    for (String line : lineList) {
        wordlists.add(Arrays.asList(line.trim().split(" ")));
    }
    return wordlists;
}

After seeing your code, I also suggest you learn Java.

The following work's

String content = jta.getText(); //jta = Instance of JTextArea
List<List<String>> list = new ArrayList<ArrayList<String>>();
for (String line : content.split("\n"))
{
String words[] = line.split("\\s");
 list.add(new ArrayList<String>(Arrays.asList(words)));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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