0

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

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

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

4

3 回答 3

3

你可以换行

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

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

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

于 2013-05-07T05:23:08.850 回答
1

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

于 2013-05-07T05:24:52.800 回答
1

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

如果start==0?它永远不会进入 if 块,也不会打印任何内容。所以改成if(start >= 0 && end < players.size()).

于 2013-05-07T05:55:27.163 回答