2012-11-03 39 views
0

雖然做了一些工作,爲我的實驗室在大學 我創建這個函數,其中有一個用於內部另一個循環。我的程序不會進入我的第二個for循環

這不是重要的是知道什麼是用於該方法。我只是不知道爲什麼程序不會進入第二個循環。這是代碼:

public void worseFit(int[] array){ 
    int tempPosition = -1; 
    int tempWeight = 101 ; 
    for (int x = 0; x < (array.length - 1); x++){ 
    if (allCrates.getSize() < 1){ 
     Crate crate = new Crate(); 
     crate.addWeight(array[0]); 
     allCrates.add(crate); 
    } else{ 
     for(int i = 1; i < (allCrates.getSize() - 1); i++){ 
     Crate element = allCrates.getElement(i); 
     int weight = element.getTotalWeight(); 
     if (weight < tempWeight){ 
      tempWeight = weight; 
      tempPosition = i; 
      Crate crate = new Crate();  
      if (weight + tempWeight <= 100){ 
      crate.addWeight(weight + tempWeight); 
      allCrates.setElement(i, crate); 
      } else { 
      crate.addWeight(weight); 
      allCrates.setElement(allCrates.getSize(), crate); 
      } // if 
     } // if 
     } // for 
    } // if 
    } // for 
} // worseFit 

一旦程序進入代碼的其他部分,它直接 退後到第一個for循環的開始。

會有人知道如何解決這個問題呢?

+3

那麼,如果從未進入for循環第二,那麼顯然條件'I <(allCrates.getSize() - 1)'總是解析爲FALSE。你確實檢查了這些價值觀,不是嗎? – arkascha

+0

在第二個for循環中放置了一些控制檯輸出,並查看它是否正在執行。 – Abubakkar

回答

1

似乎有一些出入與allCrates.getSize()的預期值。

如果allCrates.getSize()回報2,將進入第二個for循環,但不運行它,因爲i < allCrates.getSize() - 1會導致錯誤的

你可能想使用的<=代替<

0

初始化變量i在您的第二個循環中輸入0而不是1。因爲如果你的getSize()回報1也不會進入if一部分進入else部分後for循環條件將評估爲false,因此你for循環將不被執行。

相關問題