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
You were declaring data array to length
This is why the error is. Change the statement to above given code.
UPDATE
}
This will give you the desired output , add it to fill method before the return statement
Try this:
Replace your fill() method to this
Reason:
Your current
fill()
method is not saving values to the array you must ad this lineusing
you are just entering the data again and again on the
int
variablex
Update
change this
to this