开发者

Why don' t I get an output from this 2D array in Java?

I am trying to build an 2D array with the size of from 1D array and pupolate it with random numbers. Why don't I get an output when I run this code below? There is no errors in my IDE:

public void raggedArray(){
    int maxRows = 3;
    int maxCols = 4;

    int [] onedArray = new int [maxRows];
        for (int i = 0; i < maxRows; i++){
        onedArra开发者_如何学Goy[i] = (int) ((Math.random() * 100) * maxCols);
    }

    int [][] twodArray = new int[maxRows][];
        for (int i = 0; i < maxRows; i++){
        twodArray[i] = new int[onedArray[i]];
    }

        for (int i = 0; i < twodArray.length; i++){
        for (int j = 0; j < twodArray[i].length; j++){
            twodArray[i][j] = (int) (Math.random() * 100);
        }
    }

    System.out.println("2 - The 2D array: ");
    for (int i = 0; i < twodArray.length; i++){
        for (int j = 0; j < twodArray[i].length; j++){
            System.out.print(twodArray[i][j] + " ");
        }
        System.out.println("");
    }

        }


} 


Your code compiles correctly, runs and outputs some numbers. Maybe raggedArray() isn't called like Giacomo mentioned?

It might also be that the two-dimensional array is created incorrectly. I suppose this:

twodArray[i] = new int[onedArray[i]];

should be replaced with:

twodArray[i] = new int[maxCols];


I just copied your code .. compiled it , ran it and got it to print something .. not really sure what we are trying to do here, but it does print something.


I don't know what the code does, and if it's correct or not, but it should print something, absolutely. At least System.out.println("2 - The 2D array: "); is guaranteed to be executed.

Are you sure raggedArray() is ever called?

Are you sure you're looking to the right spot in your IDE? Try without the IDE, running the code from a terminal.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜