[英]Printing out values between two indexes in for loop
目前,我已經開發了一種方法,該方法可以從多個播放器(從ArrayList)獲取起始索引和結束索引之間的屬性。 盡管這聽起來很容易,但是在運行項目時,我什么都沒打印到NetBeans控制台。 這是下面的方法代碼:
/**
* 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 。
感謝您的提示和建議:)。
您可以更換線
for(i = 0; (i <= end && i >= start); i++)
同
for(i = start; i <= end; i++)
由於start>0
但i=0
,第一個版本完全沒有迭代,因此終止條件i>=start
將立即停止循環。
我猜你的意思是start>=0
。
同樣,您的for循環可能會更好for(i = start; i <= end ; i++)
您正在使用if(start > 0 && end < players.size())
。
如果start==0
怎么辦? 如果阻塞,它將永遠不會進入,什么也不會打印。 因此將其更改為if(start >= 0 && end < players.size())
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.