Search code examples
javamatrix2dsparse-matrix

passing random numbers to a 2d array in java


Why am i getting erros in my code - I created two methods, randomGen to generate a random number and matrixGen to create the matrix with random numbers. I am getting incompatible types error. If someone can please point me in the right direction to what I could be doing wrong.. Im still in learning phase.. Heres my code:

import java.util.Random;

public class sparse{
    static int matrix [][] = new int[6][6];

    public static int randomGen(){
        int rA;
        Random r = new Random();
        rA = r.nextInt(100);
        return rA;
    }

    public static int[][] matrixGen(){
        for(int i=0; matrix[i].length < i; i++){
            for(int j=0; matrix[j].length <j; j++){
                matrix[i] = matrix[i].randomGen();
                matrix[j] = matrix[j].randomGen();
            }
        }
        return matrix[i][j];
    }

    public static void main(String args[]){
        new sparse();
    }
}

Solution

  • Get rid of randomGen, use this:

    public static int[][] matrixGen(){
        Random r = new Random( );
        for(int i=0; i < matrix.length; i++){
            for(int j=0; j < matrix[i].length; j++){
                matrix[i][j] = r.nextInt( 100 );
            }
        }
        return matrix;
    }
    

    3 (update: 4) things:

    1. you're using Random wrong. You should create it once, then get lots of numbers from it.
    2. you're trying to call randomGen on an int, which makes no sense; it's a property of sparse, not int. You could have done matrix[i][j] = randomGen().
    3. you're doing something very odd indeed to access array elements. Hopefully this code will clear it up for you a bit.
    4. your loops are odd too. I've fixed them in this snippet.