2012-06-28 45 views
2

嗨,我想自動填充基於用戶輸入的二維數組。 用戶將輸入1個數字,這個數字將設置2d數組的大小。然後我想打印出數組的數字。例如,如果用戶輸入數字4,則爲 。二維數組將是4行4列,並且應該包含數字1到16,並按如下所示進行打印。如何自動填充數字的二維數組

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

但我正在努力想到會這樣做的正確聲明。 目前我的代碼只是打印出一個包含*的二維數組。

有沒有人有任何想法如何我可以打印出數字,我真的卡住了。 我的代碼如下:

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(); 
    } 
} 
+0

你在問如何在數組'grid'中輸入正確的數字嗎? – Ankit

回答

4

讀N值,

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; 
inc++; 
} 
+0

謝謝大家的意見,他們都幫助。我得到它的工作,因爲我想 – derek

1

嗯,首先你必須填寫與數字數組。你可以使用你的double for for循環和一個計數器變量,在內循環的每個循環之後你會增加它。

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

然後,您可以再次用double for循環輸出數組。

+0

感謝您的協助。我曾嘗試過類似的東西,把我在for循環中聲明的計數器變量。 – derek

0

我不確定我是否理解你的權利。 您的代碼打印*有問題嗎?

如果是的話,那麼,其原因在於這

System.out.print("*"); 

應該

System.out.print(grid[row]); 
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++; 
     } 
    } 
} 

此代碼應打印出數字如何你想要他們。

+1

循環內的'if'決定應該使用'arraySize - 1'而不是'3'。 – Baz

+0

哦,謝謝你發現我會編輯它。 – Rossiar