在for循环中打印出两个索引之间的值

时间:2013-05-07 05:18:15

标签: java oop

目前,我已经制作了一个方法,该方法从起始索引和结束索引之间的多个玩家(来自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-loop区域的某个地方,尤其是循环中的条件。我之前没有以这种方式使用这种情况,但是被告知它是合法的。我让其他人试着帮助我,但仍然没有打印出来。这可能是我不断忽视的一个非常小的错误。

如果要运行项目,可以在https://github.com/rattfieldnz/Java_Projects/tree/master/PCricketStats从GitHub克隆我的项目文件。

感谢您的任何提示和建议:)。

3 个答案:

答案 0 :(得分:3)

您可以替换

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

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

start>0 i=0以来,第一个版本根本不进行迭代,因此终止条件i>=start将立即停止循环。

答案 1 :(得分:1)

我猜你的意思是start>=0  你的for循环也可以更好for(i = start; i <= end ; i++)

答案 2 :(得分:1)

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

如果start==0怎么办?它永远不会进入if块,什么都不会被打印出来。 所以将其更改为if(start >= 0 && end < players.size())