2015-06-21 101 views
0

我正在嘗試編寫一個打印二維數組的程序,該程序的隨機數範圍從100-10000,並打印出數組中的最大數,平均值和最小值。該程序將詢問用戶行數和列數,並在該數組中打印隨機數。如何用隨機數打印二維數組

這裏是我的代碼:

Random rand = new Random(); 

int randomnumber = rand.nextInt(9901) + 100; 

Scanner console = new Scanner(System.in); 

System.out.println("Enter row"); 
int n = console.nextInt(); 

System.out.println("Enter column"); 
int y = console.nextInt(); 

int[][] array = new int[n][y]; 
array[n][y] = randomnumber; 

int k; 
for (int i = 0; i <= array.length; i++) { 
    for (k = 0; k <= array[i].length; k++) { 
     System.out.print(array[i][k]); 
    } 
} 
+2

但是,什麼是您所遇到的概率? –

+0

當我嘗試打印陣列時,它不打印 –

+0

是的,它沒有打印任何東西 –

回答

1

如果你想使用隨機值來填充數組,你需要在一個循環中產生的隨機值,然後將它們寫入到這個循環數組。到目前爲止,您只能生成一個值(並將其置於無效位置)。

此外,由於數組是基於0的,因此您的循環應爲for(i=0; i<arr.length; i++);,而不是<=

下面是一些代碼:

// don't declare k here 
for(int i=0;i<array.length;i++){ 

for(int k=0;k<array[i].length;k++){ 
     array[i][k]=rand.nextInt(9901)+100; 
     System.out.print(array[i][k]); 


} 
System.out.println(); // separate rows 
} 
+0

感謝它的工作,但我會如何使這種權利對齊。我得到的輸出,但它沒有被分開。 –

+0

@kylwalfer您需要'System.out.printf'格式正確。以下是其中一個示例:https://stackoverflow.com/questions/15215326/how-can-i-create-ascii-table-in-java-in-a-console/15215434#15215434 – Pshemo

+0

感謝您的幫助 –