Java 当有奇数队号时,我的fixture算法抛出异常
当团队列表计数为奇数时,我的fixture generator算法抛出java.lang.IndexOutOfBoundsException。我发送了21个大小的团队列表,并给出了这个例外。即使是17、19、23也会抛出相同的异常。例外情况如下:Java 当有奇数队号时,我的fixture算法抛出异常,java,algorithm,exception,fixtures,Java,Algorithm,Exception,Fixtures,当团队列表计数为奇数时,我的fixture generator算法抛出java.lang.IndexOutOfBoundsException。我发送了21个大小的团队列表,并给出了这个例外。即使是17、19、23也会抛出相同的异常。例外情况如下: E/AndroidRuntime: FATAL EXCEPTION: main Process: com.xelorium.soccerleaguetable, PID: 1189 java.lang.IndexOutOfBoundsException
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.xelorium.soccerleaguetable, PID: 1189
java.lang.IndexOutOfBoundsException: Index: 21, Size: 21
at java.util.LinkedList.checkElementIndex(LinkedList.java:555)
at java.util.LinkedList.get(LinkedList.java:476)
at com.xelorium.soccerleaguetable.FixtureGenerator.getFixtures(FixtureGenerator.java:34)
FixtureGenerator.java:
public class FixtureGenerator<T extends Object> {
public List<List<MatchModel<T>>> getFixtures(List<T> teams, boolean includeReverseFixtures) {
int numberOfTeams = teams.size();
boolean ghost = false;
if (numberOfTeams % 2 != 0) {
numberOfTeams++;
ghost = true;
}
int totalRounds = numberOfTeams - 1;
int matchesPerRound = numberOfTeams / 2;
List<List<MatchModel<T>>> rounds = new LinkedList<List<MatchModel<T>>>();
for (int round = 0; round < totalRounds; round++) {
List<MatchModel<T>> fixtures = new LinkedList<MatchModel<T>>();
for (int match = 0; match < matchesPerRound; match++) {
int home = (round + match) % (numberOfTeams - 1);
int away = (numberOfTeams - 1 - match + round) % (numberOfTeams - 1);
if (match == 0) {
away = numberOfTeams - 1;
}
//Here where it throws the exception
fixtures.add(new MatchModel<T>(teams.get(home), teams.get(away)));
}
rounds.add(fixtures);
}
公共类FixtureGenerator{
公共列表GetFixture(列表团队、布尔IncludeReverseTexture){
int numberOfTeams=teams.size();
布尔重影=假;
如果(NumberOfTeam%2!=0){
numberOfTeams++;
鬼=真;
}
int totalRounds=团队数量-1;
int matchesporound=numberOfTeams/2;
列表轮次=新建LinkedList();
对于(整数舍入=0;舍入<总舍入数;舍入++){
List fixtures=newlinkedlist();
for(int match=0;match
在这里,您正在增加团队数量,并试图匹配一个甚至不存在的团队
if (numberOfTeams % 2 != 0) {
numberOfTeams++;
ghost = true;
}
if (match == 0) {
away = numberOfTeams - 1;
}
//Here where it throws the exception
fixtures.add(new MatchModel<T>(teams.get(home), teams.get(away)));
假设您有21个团队,团队列表中的最后一个索引是20(索引从零开始)。但“numberOfTeams”是22。在这个if block中,“away”将是22-1=21,然后尝试到达列表中的21索引团队。但这个团队不存在
if (numberOfTeams % 2 != 0) {
numberOfTeams++;
ghost = true;
}
if (match == 0) {
away = numberOfTeams - 1;
}
//Here where it throws the exception
fixtures.add(new MatchModel<T>(teams.get(home), teams.get(away)));
if(匹配==0){
客场=团队数量-1;
}
//在这里,它抛出异常
fixture.add(新的MatchModel(teams.get(home)、teams.get(away));
作为一种解决方案,当团队计数为奇数时,您可以将空团队添加到列表中以进行绕过