2014-10-22 69 views
-1

我正在練習我的java並遇到一些問題。二元運算符的不良操作數類型%

我想學習從Arraylist中刪除元素,所以我要消除這些可能性。

public static void arrayLists(){ 
     List<Integer> xlist = new ArrayList<Integer>(); 
     for (int x = 0; x < 10; x ++){ 
      xlist.add(x); 
     } 
     for (Iterator<Integer> pointer = xlist.iterator(); pointer.hasNext();){ 
      if (pointer % 2 == 1){ 
       pointer.remove(); 
      } 
     } 
    } 

爲什麼不編譯? '二元運算符'的錯誤操作數類型'

我認爲問題與列表元素是整數,而我將它們與int(s)進行比較。任何想法如何解決這個問題?

+0

指針類型Iterator'的'和'不Integer'。你需要首先提取整數值來調用% – Neo 2014-10-22 06:25:30

+0

@ Mhsmith21答案posted – 2014-10-22 06:27:53

回答

0

它應該是:

 if (pointer.next() % 2 == 1){ 
      pointer.remove(); 
     } 

指針是Iterator,你不能對其執行%。您必須通過調用pointer.next()來獲取Ierator當前位置處的整數。

0

替換:

if (pointer % 2 == 1) 

if (pointer.next() % 2 == 1) 
0

有在你的代碼的一些錯誤,工作代碼爲: - 做

public static void arrayLists(){ 
    List<Integer> xlist = new ArrayList<Integer>(); 
    for (int x = 0; x < 10; x++){ //this is not a compiler error but avoid unnecassary spaces , x ++ should be x++ 
     xlist.add(x); 
     } 
    Iterator<Integer> pointer = xlist.iterator(); // write this out of the for loop statement, since we wont be needing it 
    while(pointer.hasNext()){ //its better to use while loop, since there is no increment for counter variable required, the iterator will do that job 
     if (pointer.next() % 2 == 1){ //get current element in iterator by using next() function, pointer.next() 
     pointer.remove(); 
     } 
    } 
} 
0

變化 - if (pointer.next() % 2 == 1).next實際上將返回對象 公共類的測試{

public static void main(String[] args) { 
     arrayLists(); 
    } 

    public static void arrayLists() { 
     List<Integer> xlist = new ArrayList<Integer>(); 
     for (int x = 0 ; x < 10 ; x++) { 
      xlist.add(x); 
     } 
     for (Iterator<Integer> pointer = xlist.iterator() ; pointer.hasNext() ;) { 
      if (pointer.next() % 2 == 1) { 
       pointer.remove(); 
      } 
     } 

     System.out.println(xlist); 
    } 

} 

輸出

[0, 2, 4, 6, 8] 
相關問題