Search code examples
javafor-loopuser-inputmultidimensional-array

trying to fill a 2D array by user-input how to do it?


i am creating a code that allow user to enter his input to create a 2D array but it did not work as it should i do not know where is the problem if anyone can help me i will appreciate that.

this my code :

package test7;

import java.util.Scanner;

public class test7 {

    private int row = 4;
    private int col = 4;
    private int[][] matrix;

    public test7(int trow, int tcol) {

        this.row = trow;
        this.col = tcol;
    }

    public test7(int trow, int tcol, int[][] m) {

        this.row = trow;
        this.col = tcol;
        this.matrix = m;
    }
public int[][] fill(){


        int[][] data = new int[row][col];
        Scanner in = new Scanner(System.in);

        for(int row = 0; row< matrix.length; row++){
            for(int col = 0 ;col< matrix[row].length; col++){
                System.out.println("enter the elementss for the Matrix");
                data[row][col] = in.nextInt();


            }
            System.out.println();
        }
        return data;
    }



    public static void main(String[] args){
        int[][] ma = new int[3][2];
        test7 q2 = new test7(3, 2,ma);
        q2.fill();
    }
}

the output:

enter the elementss for the Matrix
4
enter the elementss for the Matrix
3

enter the elementss for the Matrix
5
enter the elementss for the Matrix

8

enter the elementss for the Matrix
9
enter the elementss for the Matrix
0

the output should look exactly like this:

1 2

3 4

5 6


Solution

  •  public int[][] fill(){
          int[][] data = new int[row][col];  
          Scanner in = new Scanner(System.in) 
    
         .....
    
          return data; 
    
      } 
    

    You were declaring data array to length

     [0][0]
    

    This is why the error is. Change the statement to above given code.

    UPDATE

       public int[][] fill(){ 
            int[][] data = new int[row][col]; 
            Scanner in = new Scanner(System.in);
            for(int row = 0; row< matrix.length; row++){ 
                  for(int col = 0 ;col< matrix[row].length; col++){ 
                       System.out.println("enter the elementss for the Matrix"); 
                      data[row][col] = in.nextInt(); 
                   } System.out.println(); 
              } 
    
               for(int row = 0; row< matrix.length; row++){
           for(int col = 0 ;col< matrix[row].length; col++){ 
                 System.out.println(data[row][col]);
           } 
          System.out.println(); 
       }
             return data; 
    

    }

    This will give you the desired output , add it to fill method before the return statement