2017-11-18 205 views
0

我試圖從用戶採取未知數量的整數(直到用戶輸入0),並計數每個輸入的整數。我想,在完成整數之後算數,我不得不將它們存儲在一個數組中。我做了一些研究並意識到創建一個長度未指定的Array的唯一方法是ArrayList是唯一的方法。但我的代碼,這部分顯示錯誤:無法使用Arraylist.get方法,它顯示「不兼容的操作數類型對象和int」

import java.util.Scanner; 

import java.util.ArrayList; 

public class IntegersOccurence { 

    public static void main(String[] args) { 
     Scanner input = new Scanner (System.in); 

     System.out.print("Enter the integers between 1 and 100: "); 
     ArrayList list = new ArrayList(); 
     System.out.println(list.get(0)); 
     //eclipse is showing an error in the line right below 
     while (list.get(list.size() - 1) != 0) { 
      list.add(input.nextInt()); 
     } 
    } 
} 
+0

也許你可以參考[這裏](https://stackoverflow.com/questions/18513308/what-is-the-difference-between-arraylist- arraylist-arraylistobject),因爲它可以回答你的問題:) – nkpg

回答

0

的話,最好使用此代碼:

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

public class IntegersOccurence { 

    public static void main(String[] args) { 
     Scanner input = new Scanner (System.in); 

     System.out.print("Enter the integers between 1 and 100: "); 
     List<Integer> list = new ArrayList<Integer>(); 
     list.add(input.nextInt()); 
     System.out.println(list.get(0)); 
     //eclipse is showing an error in the line right below 
     while (list.get(list.size() - 1) != 0) { 
      list.add(input.nextInt()); 
     } 
    } 
} 
2

您使用raw type所以列表的類型爲Object不能相比int0),因此使用

ArrayList<Integer> list = new ArrayList<>(); 

Read , What is a raw type and why shouldn't we use it?


As mentioned:您在中沒有添加任何元素和調用get會導致崩潰,因爲

From docs

IndexOutOfBoundsException - if the index is out of range (index < 0 || index >= size()

這裏index>=size()是真實的(列表的大小爲0,沒有元素),所以因此例外

0

更改如下行:

ArrayList list = new ArrayList(); 

收件人:

ArrayList<Integer> list = new ArrayList<>(); 

默認情況下,您的列表類型是Object,通過定義數據類型我們避免了運行時類型錯誤,並且檢查在編譯時完成。

+0

謝謝!這有助於消除錯誤!但它仍然顯示「線程中的異常」主「」 public static void main(String [] args){ \t \t Scanner input = new Scanner(System.in); System.out.print(「輸入1到100之間的整數:」);};
\t \t \t \t ArrayList list = new ArrayList <>();
\t \t boolean val = true;
\t \t而(VAL ==真){
\t \t \t \t \t \t如果(list.get(名單。size() - 1)== 0){
\t \t \t \t val = false;
\t \t \t}
\t \t \t否則{
\t \t \t \t list.add(input.nextInt());
\t \t \t}
\t \t}
\t \t \t \t}
} –

+0

有什麼異常?在線程異常 「主」 java.lang.ArrayIndexOutOfBoundsException: – HaroldSer

+0

輸入整數1到100之間-1 \t在java.util.ArrayList.elementData(未知來源) \t在java.util.ArrayList.get(未知源) \t at IntegersOccurence.main(IntegersOccurence.java:16) –

相關問題