5

Hi i am trying to auto populate a 2d array based on user input. The user will enter 1 number, this number will set the size of the 2d array. i then want to print out the numbers of the array. for example , if the user enters the number 4 . the 2d array will be 4 rows by 4 colums, and should contain the number 1 to 16, and print out as follows.

1-2-3-4
5-6-7-8
9-10-11-12
13-14-15-16

But i am struggling to think of the right statement that will do this. for the moment my code just prints out a 2d array containing *.

Has anyone any ideas how i could print out the numbers , i'm really stuck. my code follows:

public static void main(String args[]){

    Scanner input = new Scanner(System.in);
    System.out.println("Enter room length");

    int num1 = input.nextInt();
    int num2 = num1;
    int length = num1 * num2;
    System.out.println("room "+num1+"x"+num2+"="+length);

    int[][] grid = new int[num1][num2];

    for(int row=0;row<grid.length;row++){   
        for(int col=0;col<grid[row].length;col++){
            System.out.print("*");  
        }
        System.out.println();
    }
}
mtk
  • 13,221
  • 16
  • 72
  • 112
derek
  • 1,025
  • 9
  • 22
  • 32

4 Answers4

4

Read n value,

int[][] arr = new int[n][n];
int inc = 1;
for(int i = 0; i < n; i++)
    for(int j = 0; j < n; j++) 
        arr[i][j] = inc++;
    
Pshemo
  • 122,468
  • 25
  • 185
  • 269
Theja
  • 744
  • 1
  • 7
  • 24
2

Well, first of all you have to fill the array with the numbers. You can use your double for loop for this and a counter variable which you increment after each loop of the inner for loop.

int counter = 1;
for(int x = 0; x < num1; x++)
{
    for(int y = 0; y < num2; y++)
    {
        grid[x][y] = counter++;
    }
}

Afterwards you can output the array again with a double for loop.

Baz
  • 36,440
  • 11
  • 68
  • 94
0

I am not sure if I understand you right. You have problem with the code printing *?

If yes, then the reason for that is this

System.out.print("*");

Should be

System.out.print(grid[row]);  
mulayamod
  • 1
  • 2
0
public static void main(String[] args) {

    Scanner input = new Scanner(System.in);
    System.out.println("Enter room length");
    int arraySize = input.nextInt();
    System.out.println("Length: " + (arraySize*arraySize));

    int[][] array = new int[arraySize][arraySize];
    int count = 1;

    for (int i=0;i<arraySize;i++) {
        for (int j=0;j<arraySize;j++) {
            array[i][j] = count;
            if (j != (arraySize-1)) 
                System.out.print(count + "-");
            else
                System.out.println(count);
            count++;
        }
    }
}

This code should print out the numbers how you want them.

Rossiar
  • 2,416
  • 2
  • 23
  • 32
  • 1
    The `if` decision within the loops should use `arraySize - 1` rather than `3`. – Baz Jun 28 '12 at 11:55