2014-11-24 78 views
0

我正在嘗試爲BlueJ(Java)中的程序編寫一些代碼,該代碼列出了行李並添加並從這些行李中刪除了物品。然後我陷入了第一堂課;我無法正確添加一個項目到包中,正如您在addItem()方法中注意到的那樣;它不斷添加String到數組中的每個null元素,而不是第一次遇到。任何幫助將非常感激。Java Arrays [] - 將For循環中的特定元素賦值爲某些值

最良好的祝願&千恩萬謝,

的Xenos

public class Bag1 { 
    private String[] store; // This is an array holding mutlitple strings. 

    public Bag1(int storageCapacity) { 
     store = new String[storageCapacity]; 
    } // That was the primitive array constructor. 

    public boolean isFull() { 
     boolean full = true; 
     for(int i = 0; i < store.length; i++) { 
      if(store[i] == null) { 
       full = false; 
      } 
     } 
     return full; 
    } // The method above checks if the bag is full or not, and returns a boolean value on that basis. 

    public void add(String s) { 
     for(int i = store.length; i >= 0; i--) { 
      if(store[i] == null) { 
       store[i] = s; 
      } 
     } 
    } 
} 
+3

第一件事就是馬上着手準備出你的代碼一個相當傳統的方式 - 不要在一行上放置大量的語句,把右括號放在單獨的一行中,等等。您的代碼將更容易以這種方式讀取... – 2014-11-24 11:41:29

+0

你有沒有學過'break;'或'return;',因爲這就是你需要的。或者一個布爾變量表明你已經添加了一些東西,並且循環應該停止。請學會縮進你的代碼,以便你自己理解你自己的代碼。同樣,數組中的索引從0到length - 1。所以這段代碼應該是ArrayIndexOutOfBoundsException。 – 2014-11-24 11:42:19

回答

0

找到第一個空白點之後,應該退出循環:

public void add(String s) 
{ 
    for(int i=store.length-1; i>=0; i--) { // note the change in the starting index 
     if(store[i]==null) { 
      store[i] = s; 
      break; 
     } 
    } 
}