2016-03-27 31 views
-2

我是Java編程的新手,我在程序中遇到了麻煩。 我有一個數組,我想從中提取最大整數並將其返回給主程序。但是沒有使用ArrayList。 當我打印它時,我不能在這個特定的位置上有0,所以我不能更換它。看看我到目前爲止做了什麼,但我認爲這是錯誤的。如何從數組中刪除整數Java

public int extractMax() 
    { 
     for (int i = 0; i < size; i++) 
     { 
      if(maxInsert == Queue[i]) 
      { 
       Queue[i] = null; 
       return maxInsert; 
      } 
     } return -1; 
    } 
+0

我不知道該怎麼辦....我沒有做到目前爲止 –

+0

爲什麼downvotes?這對我來說很清楚.. –

+0

我不確定我真的明白你在做什麼?你是否試圖迭代數組來找到最大的整數,並且一旦找到了返回值?或者你是否正在嘗試我剛纔所說的,但實際上是從數組中刪除最大值? – Afflicted

回答

0

所以這裏的邏輯是基本通過數組的每個元素進行迭代,以查看是否有一個元素比目前最大的較大元素(從第一個元素開始)在數組中。如果找到更大的元素,則最大變量將重置爲此新值,並且循環繼續。如果找到更大的元素,那麼通過更新最大變量會發生同樣的情況。要從數組中實際刪除此元素,可以創建一個大小小於原始大小的新數組,將所有元素一直到最大值複製到新數組中,然後將所有元素移到最右側由左向右。這是它應該看起來像。

public int extractMax() 
     { 
      maxInsert = Queue[0]; 
      int maxIndex = 0; 
      for (int i = 1; i < size; i++)//get the location of the max element 
      { 
       if(maxInsert < Queue[i]) 
       { 
        maxInsert = Queue[i]; 
        maxIndex = i; 
       } 
      } 
      int[] temp = new int[Queue.length - 1]; 
      for(int j = 0; j < maxIndex; j++){ //adding elements up until the max 
       temp[j] = Queue[j]; 
      } 
      for(int k = maxIndex; k < temp.length; k++){ //adding elements after the max 
       temp[k] = Queue[k+1]; 
      } 
      Queue = temp; //queue is now this new array we've just made 
      return maxInsert; 
     } 
+0

是的,這是重點,但我也希望這個元素從陣列中刪除! –

+0

我明白了,請參閱我的編輯 –

0

您不能分配空,如果在原語的數組的數組,你會看到類似這樣的錯誤:

無法從空轉變爲int

如果陣列是一個對象數組(例如Integer),然後將它分配給null將會起作用,但是我會建議如果你需要操縱你使用List的數組條目。

例如:

List<Integer> integers = new ArrayList<>(Arrays.asList(new Integer[]{1,2,3,4,5,6,7,8,9,10})); 
System.out.println(integers.size()); 
integers.remove(new Integer(3)); 
System.out.println(integers.size()); 

將打印:

10 
9 
0

基本上你不能從ArrayList對象中刪除元素等。因此,請創建一個新的Array並將Queue中的所有元素(除了較大的元素除外)添加到新的Array。最後,將新陣列分配到Queue。這裏是一個示例代碼:

public int extractMax() 
{ 
    for (int i = 0; i < size; i++) 
    { 
     if(maxInsert == Queue[i]) 
     { 
      removeFromArray(i); 
      return maxInsert; 
     } 
    } return -1; 
} 


private void removeFromArray(int i) { 
    int[] newQueue = new int[Queue.length-1]; 

    int k = 0; 
    for (int j = 0; j < newQueue.length; j++,k++) { 
     if(i == j) { 
      k++; 
     } 

     newQueue[j] = Queue[k]; 
    } 

    Queue = newQueue; 
}