2013-05-07 57 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