Using java scanner class failed to retrive data from txt file and set it into the targated 2d array

28 Views Asked by At

the supposed output should have first 6 null repalced by 6 inner array like {1, 2, 3}, it seems the targeted array combinedArray has not get data from the file1 using scanner.

Output:[null, null, null, null, null, null, null, null, null, null, null, null]

'''

public static void main(String[] args) throws FileNotFoundException {
    Scanner file1 = new Scanner(new File("C:\\Users\\admin\\IntellijProjects\\AlgorithmsProblemSolving2\\numbers1.txt"));
    Scanner file2 = new Scanner(new File("C:\\Users\\admin\\IntellijProjects\\AlgorithmsProblemSolving2\\numbers2.txt"));

    //loop through two files to get the total rows of the new combined 2d array
    int rowFile1 = 0;
    while (file1.hasNextLine()) {
        rowFile1++;
        file1.nextLine();
    }
    int rowFile2 = 0;
    while (file2.hasNextLine()) {
        rowFile2 ++;
        file2.nextLine();
    }
    
    int totalRow = rowFile1 + rowFile2;
    //total rows from two txt files, Initialize the 2d Array combinedArray
    int[][] combinedArray = new int[totalRow][];


    //insert files1's element into combinedArray
    while (file1.hasNextLine()) {
        for (int k = 0; k < rowFile1; k++) {
           int count = 0;
           int len = file1.nextLine().length();
           if (count < len) {
               combinedArray[k][count] = file1.nextInt();
               count ++;
           }
           file1.nextLine();
        }
    }
    System.out.println(Arrays.deepToString(combinedArray));
}

'''

0

There are 0 best solutions below