2016-04-15 46 views
1

我想在我的名單打印出最大數量..我實現了在Java這個代碼..打印出數量最多的ArrayList

import java.util.ArrayList; 
import java.util.Scanner; 

public class Product { 

public static void main(String[] args) { 
    ArrayList<Integer> list = new ArrayList<Integer>(); 
    System.out.println("Enter your number"); 
    Scanner scan = new Scanner(System.in); 
    int n=0; 
    while (n<3) { 
    int num = scan.nextInt(); 
    n++; 
    } 
    int max = Integer.MIN_VALUE; 
    for (int i =0; i<list.size(); i++) { 
     if (list.get(i)>max) { 
      max=list.get(i); 
     } 
    } 

    System.out.println(max); 


     } 
    } 

當我運行這段代碼我總是-2147483648在輸出.. 我在代碼中做了什麼錯誤?

謝謝

+3

因爲'list'是空的。你永遠不會向它添加元素。 – Tunaki

+0

謝謝你......但我通過使用掃描儀添加號碼,因爲我實施了 –

+0

你永遠不會將項目添加到'list'。 –

回答

3

你做錯了什麼?

您可以輸入數字,但不要將它們存儲在ArrayList中。 因此,您的ArrayList始終爲空,並且min始終保持爲Integer.MIN_VALUE

您需要存儲它們。將您的while循環更改爲:

while (n<3) { 
    int num = scan.nextInt(); 
    list.add(num); 
    n++; 
} 
+1

哦,我的上帝......謝謝你兄弟:)我錯過了這個\t'list.add(num);' –