gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 17:24:01 25 4
gpt4 key购买 nike

目前,我已经制定了一种方法,可以从起始索引和结束索引之间的多个玩家(从 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 将立即停止循环。

关于java - 在 for 循环中打印两个索引之间的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16411691/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com