mardi 19 décembre 2017

How do I fill a 2d matrix with math.random or null in Java?

I want to either fill in with null or with random numbers (0..50) a matrix. If "random" is true (it could be either boolean true or false, or int 0 or 1 doesn't matter) , then it will fill the matrix with random numbers up to 50, else , it will fill it with null.

public class array 
   {
    protected int N;
    protected int M;
    protected int [][] matrix;

    array(int n, int m, boolean random)
    {
        N=n;
        M=m;
        matrix=new int[n][m];

        if (random==true)

        {
                for(int i=0;i<N;i++)
                    for(int j=0;j<M;j++)
                        matrix[i][j]=null;
        }
        else
        {
            for(int i=0;i<N;i++)
                for(int j=0;j<M;j++)
                {
                   matrix[i][j]=(int)(Math.random()*50);
                }
        }
    }

And then, I'd like to display this

    public void display() {
    System.out.println("[ Dimensions = " + this.N + " x " + this.M + " ]");
    for(int i=0;i<N;i++)
    {
        for(int j=0;j<M;j++)
            if (matrix[i][j])!=null) 
            {
                System.out.print(" ["+matrix[i][j].displayString()+"]");
            }
            else
                {System.out.print("[null]");
           System.out.println("");
    }
    System.out.println("");
}
}

Is it correct? I get an ''illegal start of expression'' to the if , within display(), among others.




Aucun commentaire:

Enregistrer un commentaire