I have a text file that is in the project directory. In it, separated by a dot, are groups of professions. for example

Programmer: Web Designer: System Administrator. Biologist: Pharmacist: Chemistry Teacher.

My task is to fill the String array with groups of these professions. Points are the separators of the elements of the array. In my example, there would be an array of two elements.

There are 100 such groups in my file. I need to add all these groups to the array of size [10] [10] so that after each element of a multiple of 10, the cycle moves to the next line, respectively.

My code (non-working)

public static void main(String[] args) throws FileNotFoundException { String[][] array = new String[10][10]; try (BufferedReader br = new BufferedReader( new FileReader("C:\\Users\\Alexey\\eclipse-workspace\\Plugin\\src\\MatProList.txt"))) { for (int i = 0; i < 10; i++) { for (int c = 0; c < 10; c++) { while ((char)br.read() != '.') { array[i][c] = array[i][c] + (char)br.read(); } } if (br.read() == -1) { break; } } } catch (IOException ex) { System.out.println(ex.getMessage()); } } 

Please help me find my mistake.

  • to the next line in the file or to the next array? - Victor
  • I meant that the index [1] [1] was changed to the index [2] [1]. That is, when reading every tenth group of professions from a file, my first array index changed. - alexeypm
  • Error message? - Roman C

1 answer 1

In your case, I would read everything from a file and do it through arrays:

  import java.util.Arrays; public class ArrayApp { public static void main(String[] args) { //Подготовка тестовых данных StringBuilder stringBuilder = new StringBuilder(); for (int i = 1; i <= 100; i++) { stringBuilder.append(i); if (i % 10 == 0) { stringBuilder.append("."); } else { stringBuilder.append(":"); } } //Здесь должно происходить получение всех данных из файла String result = stringBuilder.toString(); System.out.println(result); //Начало обработки и формирование массива String[] array = result.split("\\."); System.out.println(Arrays.toString(array)); int length = array.length; String[][] resultArray = new String[10][10]; for (int i = 0; i < length; i++) { String[] valArray = array[i].split(":"); int lengthC = valArray.length; for (int c = 0; c < lengthC; c++) { resultArray[i][c] = valArray[c]; } } System.out.println(Arrays.toString(resultArray)); } } 

As for your code, I would read the data in a while loop and save it to StringBuilder until I met the period, then I would process the string. For this, I would start an external variable counter for counting 10.

  • I solved the problem a little differently - without reading the file, but my approach is irrational, so now I am mastering the database. Anyway, thanks. I think your answer most fully reflects the solution of the task I set. - alexeypm