Hello,
I am trying to read a simple .txt file of ints into a 2D array. However, the scanner object seems to skip the first few ints. The "scanner.hasNext()" seems to advance the scanner. Please let me know what I am doing wrong. I attached the file "input.txt" Thanks
public int[][] getMatrix(String fileName) { int totalrows = 0; int totalcols= 0; int[][] matrix = null; File file = null; Scanner scanner = null; int rowIndex = 0; int colIndex = 0; try { scanner =new Scanner(new File("input.txt")); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); System.out.println ("File not found!"); // Stop program if no file found System.exit (0); } while (scanner.hasNext()) { if (scanner.hasNextInt()) totalrows = scanner.nextInt(); if (scanner.hasNextInt()) totalcols = scanner.nextInt(); else scanner.next(); } matrix = new int[totalrows][totalcols]; while (true) { if (!scanner.hasNextInt() || !(scanner.next() == "\r") || !(scanner.next() == " ")) break; matrix[rowIndex][colIndex] = scanner.nextInt(); rowIndex++; if (scanner.next() == "\r") { rowIndex = 0; colIndex++; } } return matrix; }