2012-11-19 44 views
0

我一直在試圖找出如何找到隨機數組的最大值。這裏是我正在調試的代碼:截至目前,我所得到的只是數組中的一個值,但它不是最大值。找到隨機數的最大值

public static void main(String[] args) { 
     System.out.println(intOfMaxInRange(randomIntArray(10), 1,30)); 
    } 
    public static int random(int low, int high){ 
     int x=(int)(Math.random()*high+low); 
     return x; 
    } 
    public static int[] randomArray(int n){ 
     int[] a = new int[n]; 
     for (int i = 0; i<a.length; i++) { 
     a[i] = randomInt (1,30); 
    } 
     return a; 
    } 
    public static int intOfMax(int[] array){ 
     int max=array[0]; 
     for(int i=1;i<array.length;i++){ 
      if (array[i] > max) { 
     } 
     } 
     return max; 

    } 
+0

您在'如果什麼都不做'聲明。它如何工作?在「if」中指定'max = array [i]'。 – Maroun

+2

'intOfMaxInRange()'定義在哪裏?爲什麼你的縮進都不可思議?請花點功夫讓你的問題可讀。 – millimoose

回答

7

你是正確的方式,只需添加max = array[i];intOfMax()方法:

for(int i=1;i<array.length;i++) 
{ 
    if (array[i] > max) 
     { 
      max = array[i]; 
     } 
} 
+0

謝謝我不相信我忘記了。本網站上的每個人都非常有幫助。再次感謝。 – Lock1618

1
if (array[i] > max) { 
    } 

你這裏忘了這些線:

max = array[i];