2013-05-07 90 views
0

此刻,我已經制定了一個方法,可以從開始索引和結束索引之間的多個玩家(從ArrayList)獲取屬性。雖然這聽起來很簡單,但運行該項目時我沒有得到任何輸出到NetBeans控制檯。下面是方法代碼如下:打印for循環中兩個索引之間的值

/** 
* This overloaded method will print out the details of each player - 
* that appear between "start" and "end" indexes of the players list. 
* 
* @param players The list of players to be printed out. 
* @param start The list position of the first player. 
* @param end The list position of the last player. 
*/ 
public void listNPlayers(ArrayList<Player> players, int start, int end) 
{ 
    System.out.println(csvHeader + "\n"); 
    int i; 
    //If start is greater than 0, and end is less than the total number of players in the list 
    if(start > 0 && end < players.size()) 
    { 

     for(i = 0; (i <= end && i >= start); i++) 
     { 
      System.out.println(players.get(i).toString()); 
     } 
    } 
    else 
    { 
     //if start is less than 0, tell the user to not use a negative value 
     if(start < 0) 
     { 
      throw new ArithmeticException("You cannot use a negative index value for 'start'."); 
     } 
     //if end is greater than the size of the players list, tell the user that the value is too large. 
     else if(end > players.size()) 
     { 
      throw new ArithmeticException("Your 'end' value cannot be greater than the size of your 'players' list."); 
     } 
    } 
} 

我認爲問題存在於for循環區域的某處,尤其是循環中的條件。我以前沒有以這種方式使用這個條件,但被告知它是合法的。我有其他人試圖幫助我,但仍然沒有打印出來。這可能是我不斷忽略的一個非常小的錯誤。

如果你想運行項目,你可以從GitHub克隆我的項目文件在https://github.com/rattfieldnz/Java_Projects/tree/master/PCricketStats

感謝您的任何提示和建議:)。

回答

3

可以更換線路

for(i = 0; (i <= end && i >= start); i++) 

for(i = start; i <= end; i++) 

第一個版本不重複,因爲在所有start>0i=0,從而終止條件i>=start將立即停止循環。

+0

這正是我應該使用的,我不知道爲什麼我把我在代碼中的條件。感謝您的複習:)。 – Rob 2013-05-08 21:32:26

1

我猜你的意思是start>=0
此外,您的for-loop可能更好,因爲for(i = start; i <= end ; i++)

1

您正在使用if(start > 0 && end < players.size())

如果start==0怎麼辦?它將永遠不會進入,如果塊和沒有打印。 因此將其更改爲if(start >= 0 && end < players.size())

+0

感謝您的反饋 - 我在進一步測試後意識到這一點。已經實施了你建議的改變:)。 – Rob 2013-05-08 21:34:59