At the moment I want to write a program that would put the text from the txt file into a two-dimensional array ArrayList<ArrayList<String>> (an array of strings in which lie arrays of words).

The goal, to achieve the output:

 [ [набор слов 1й строки] [набор слов 2й строки] [ 3й...] [...n] ] 

I'm currently out:

 [ [набор слов всех строк] [набор слов всех строк] [...] ] 

Code:

  ArrayList<ArrayList<String>> str = new ArrayList<ArrayList<String>>(); ArrayList<String> words = new ArrayList<String>(); Scanner s = new Scanner(new File("C:\\Text.txt")); while (s.hasNextLine()) { // проверяем, есть ли строка String line; // временная переменная line = s.nextLine(); StringTokenizer st = new StringTokenizer(line, " "); // дробим строку на слова while (st.hasMoreTokens()) { words.add(st.nextToken()); // заносим слова в ArrayList words } str.add(words); // заносим ArrayList words в ArrayList str } System.out.println(str); 

Please, stick your nose where the error? How to write correctly?

    3 answers 3

    You have an ArrayList of all words constructed only once, but on every iteration of the loop.

      ArrayList<ArrayList<String>> str = new ArrayList<ArrayList<String>>(); ArrayList<String> words; Scanner s = new Scanner(new File("C:\\Text.txt")); while (s.hasNextLine()) { words = new ArrayList<String>(); String line = s.nextLine(); StringTokenizer st = new StringTokenizer(line, " "); while (st.hasMoreTokens()) { words.add(st.nextToken()); } str.add(words); } System.out.println(str); 

    In your variant, at each iteration, you throw into str link to the same words object, which by the end of the process contains all the words that it accumulates.

      If you are not going to add / delete already entered words, then it is more efficient to place the words of each read string in String [], and not in ArrayList <string>. The size of each such array can be obtained from st.countTokens ();

        How to write correctly?

        Here are some recommendations:

         // эту операцию надо делать до того как выделяем память на обьекты ниже // в случае если выкинет exception нашей програме пришлось бы выполнить // одну абсолютно бесполезную операцию Scanner s = new Scanner(new File("C:\\Text.txt")); // используйте интерфейсы вместо реализаций // для того чтоб изменить arraylist на другую реализацию list // достаточно изменения одной сточки List<List<String>> str = new ArrayList<ArrayList<String>>(); // обьявлять переменные в цикле плохая примета! String line; StringTokenizer st; List<String> words; while ( s.hasNextLine() ) { words = new List<String>(); line = s.nextLine(); // в таких случаях как этот от переменной line можно отказатся // (переменная используется лиш один раз) // если от этого не страдает читаемость кода (изменить и проверить) // при замене нужно добавлять хороший комментарий, напр: // строку считанную с консоли готовим к ампутации конечностей :) st = new StringTokenizer(line, " "); while (st.hasMoreTokens()) { words.add(st.nextToken()); } str.add(words); } System.out.println(str);