0

there is an issue in data.txt we have 4 rows and 3 cols and gives me error out of bound kindly someone solve this but when I pass 4x4 in rows and cols it works well but it didnt meet project requirement

public class ReadMagicSquare {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws FileNotFoundException {
        // TODO code application logic here
        
        Scanner sc = new Scanner(new BufferedReader(new FileReader("data.txt")));
      int rows = 4;
      int columns = 3;
      int [][] myArray = new int[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] = Integer.parseInt(line[j]);
            }
         }
      }
      
      for(int i=0;i<myArray.length;i++){
          for(int j=0;j<myArray.length;j++){
              System.out.print(myArray[i][j]+" ");
          }
          System.out.println();
      }
        
    }
    
}

in data.txt file

2 -1 1
6 4 24
2 19 7
Sachin Tyagi
  • 2,814
  • 14
  • 26
  • 2
    It seems to be this: `for(int j=0;j `for(int j=0;j –  Jul 08 '20 at 16:55
  • 1
    Does this answer your question? [What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?](https://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it) –  Jul 08 '20 at 16:59

2 Answers2

0
for(int i=0;i<myArray.length;i++){
          for(int j=0;j<myArray.length;j++){
              System.out.print(myArray[i][j]+" ");
          }
          System.out.println();
}

myArray.length gives you the number of rows in the 2D array, so in the inner loop, j would go from 0 to less than 4 instead of 0 to less than 3, which would give you an out of bound error.

You need to iterate j from 0 to the number of columns.

c_anirudh
  • 375
  • 1
  • 22
0

Here is the code where it calculates the dimensions of the matrix in the file, read it from the file and construct the matrix and prints it.

public static void main(String[] args) throws FileNotFoundException {

    Scanner sc = new Scanner (new File("data.txt"));
    Scanner inFile = new Scanner (new File("data.txt"));

    /*To get the dimension of the matrix*/
    String[] line = sc.nextLine().trim().split("\\s+");
    int row = 1, column = 0;
    column=line.length;
    while (sc.hasNextLine()) {
        row++;
        sc.nextLine();
    }
    sc.close();

    /*To read the matrix*/
    int[][] matrix = new int[row][column];
    for(int r=0;r<row;r++) {
        for(int c=0;c<column;c++) {
            if(inFile.hasNextInt()) {
                matrix[r][c]=inFile.nextInt();
            }
        }
    }
    inFile.close();

    /*To print the matrix*/
    System.out.println(Arrays.deepToString(matrix));
}
Ridwan
  • 214
  • 4
  • 17