Re: 1st time using methods
Quote:
how can i get a hold of the numbers the user just entered for the matrix?
You've passed the array as a parameter, so just loop through the array by row/colum
Code :
for ( int i = 0; i < mat.length; i++ ){
for ( int j = 0; j < mat[i].length; j++ ){
//do something with mat[i][j]
}
}
Re: 1st time using methods
i already tried that code
Code java:
public static void printMat(int [][] mat, int size){
for ( int i = 0; i < mat.length; i++ ){
for ( int j = 0; j < mat[i].length; j++ ){
System.out.println(mat[i][j]);
}
}
}
but the value of mat[i][j] is 0 which never changed even if the user inputed diff. values.. heres my whole code
still dont know how to access the inputted values.:(
Code java:
public static int loadMat(int [][] mat) throws Exception{
int size, row, col = 0, num;
Scanner input = new Scanner(System.in);
System.out.print("Enter the size of the square : ");
size = input.nextInt();
mat = new int [size][size];
System.out.println();
System.out.println("Enter the value for");
for (row = 0 ; row < size ; row++){
for (col = 0 ; col < size ; col++){
System.out.print("ROW " + row +" COL " +col +" : ");
num = input.nextInt();
mat[row][col] = num;
}
}
return size;
}
public static void printMat(int [][] mat, int size){
for ( int i = 0; i < mat.length; i++ ){
for ( int j = 0; j < mat.length; j++ ){
System.out.println(mat[i][j]);
}
}
}
public static void main(String[] args) throws Exception{
int [][] themat = new int [10][10];
int thesize;
int magicnum;
boolean row,col,diag;
thesize = loadMat(themat);
printMat(themat, thesize);
}
}
Re: 1st time using methods
Didn't spot this earlier (obviously), but you re-assign the variable mat in the load method, once the load method exits that variable is out of scope (and the parameter unchanged - pass by value ). I'd recommend returning the array from the load method, then send that into the print method. Lastly, take a look at the print method because it doesn't fully implement my suggestion above.
Re: 1st time using methods
yeah but my homework specifically said that the data should be stored in the reference variable called mat and the size of the method should be the value returned
uhh you said to return the array in the load method but as far as i know you can only return one value i think
Re: 1st time using methods
Well technically the size is returned with the array (via the length property). But regardless, you cannot recreate the reference to the array in the method and hope that change takes effect outside of the method. Return the array, create an object which contains the array as an instance variable and pass that through the functions, or create 2 functions, one which asks for the size, create the array using that value, and pass that created array to another function that fills in the array.