简体   繁体   中英

Creating a 2D Array and filling the array with random numbers

double numbers[][];
numbers = new double[22][9];

for(int x = 0; x<22; x++) {
    for(int y = 0; y <9; y++)
    {
        numbers[x][y] = (int)(Math.random()*192)+1;
        System.out.print(numbers[x][y]+ "");
        System.out.println();
    }

Trying to display the array within a table/index but when I do, it just display the random numbers vertically. Idk how to fix it. Sorry for the nooby code.. :(

In java two-dimensional array in java is just an array of array, and a small mistake while iterating it. Add System.out.println(); in outer for loop

for(int x = 0; x< 22; x++) {     // for every array in outer array
     for(int y = 0; y < 9; y++)  {   //for every double in each inner array

          numbers[x][y] = (int)(Math.random()*192)+1;
          System.out.print(numbers[x][y]+ "  ");     
      }
 System.out.println(); 

}

If you separate construction and display, it may be clearer:

double numbers[][] = new double[22][9];

// construction
for(int x = 0; x<22; x++)
    for(int y = 0; y <9; y++)
        numbers[x][y] = (int)(Math.random()*192)+1;

// display
for(int x = 0; x<22; x++){
    for(int y = 0; y <9; y++)
        System.out.print(numbers[x][y]+ "\t");
    System.out.println("");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM