Home > front end >  How to put each word in a sentence inside a 2d array from a csv file
How to put each word in a sentence inside a 2d array from a csv file

Time:05-25

I'm trying to read a text file and put each comma separated value in an array and put all of them inside a 2d array.But the code I have right now puts the whole line in the array

Scanner sc = new Scanner(new BufferedReader(new FileReader(path)));
        int rows = 3;
        int columns = 1;
        String[][] myArray = new String[rows][columns];
        while (sc.hasNextLine()) {
            for (int i = 0; i < myArray.length; i  ) {
                String[] line = sc.nextLine().trim().split(" "   ",");
                for (int j = 0; j < line.length; j  ) {
                    myArray[i][j] = line[j];
                }
            }
        }
        System.out.println(Arrays.deepToString(myArray));

This is the text file:

A6,A7
F2,F3
F6,G6

Output

[[A6,A7], [F2,F3], [F6,G6]]

Expected Output

[[A6],[A7],[F2],[F3],[F6],[G6]]

CodePudding user response:

i think you have to double the rows size and for each line just put one element and increment the i

CodePudding user response:

The problem is that you are assigning the entire 2D array instead of just each item.

Here are several alternatives.

  • Use Files.lines to stream the file.
  • splitting on a comma creates the 1D array of two elements for each line
  • flatMap that to stream each item.
  • that map that to an array of one item.
  • then just store them in a 2D array.
String[][] array = null;
try {
    array = Files.lines(Path.of("f:/MyInfo.txt"))
            .flatMap(line->Arrays.stream(line.split(","))
                 .map(item->new String[]{item}))
            .toArray(String[][]::new);
} catch (IOException ioe) {
    ioe.printStackTrace();
}
if (array != null) {
    System.out.println(Arrays.deepToString(array));
}

prints

[[A6], [A7], [F2], [F3], [F6], [G6]]

Here is an approach similar to yours.

List<String[]> list = new ArrayList<>();
try {
    Scanner scanner = new Scanner(new File("f:/MyInfo.txt"));
    while (scanner.hasNextLine()) {
        String[] arr = scanner.nextLine().split(",");
        for (String item : arr) {
            list.add(new String[]{item});
        }
    }
} catch (IOException ioe) {
    ioe.printStackTrace();
}

There is no deepToString for Lists so you either iterate it or convert to a 2D array.

String[][] ar = list.toArray(String[][]::new);
System.out.println(Arrays.deepToString(ar));

prints

[[A6], [A7], [F2], [F3], [F6], [G6]]
  • Related