BowlingTeamDemo2
类中的最后一个for循环在第一次迭代中将x
增加到4
的值。难倒...程序将自动填充名称而不是使用扫描仪,仅用于测试目的。我在最后一个for循环的内循环之前和之后添加了变量x
的打印输出,以测试x
的值。在内循环之前,值为0
,在内循环开始后,值为4
。
循环正确打印团队名称,但在尝试从getMember()
类访问BowlingTeam
方法时失败。这是一个例子,而不是练习。
我得到的错误是:
线程中的异常" main" java.lang.ArrayIndexOutOfBoundsException:4 在BowlingTeam.getMember(BowlingTeam.java:21)at BowlingTeamDemo2.main(BowlingTeamDemo2.java:41)
public class BowlingTeam{
private String teamName;
private String[] members = new String[4];
public void setTeamName(String team){
teamName = team;
}
public String getTeamName(){
return teamName;
}
public void setMember(int number, String name){
members[number] = name;
}
public String getMember(int number){
// We have an issue here!!!!!!
return members[number];
}
}
import java.util.*;
public class BowlingTeamDemo2{
public static void main(String[] args){
String name;
final int NUM_TEAMS = 4;
final int NUM_TEAM_MEMBERS = 4;
int x;
int y;
BowlingTeam[] teams = new BowlingTeam[NUM_TEAMS];
Scanner input = new Scanner(System.in);
for(y = 0; y < NUM_TEAMS; ++y){
teams[y] = new BowlingTeam();
System.out.println("Enter team name >> ");
name = "Teams";
teams[y].setTeamName(name);
for(x = 0; x < NUM_TEAM_MEMBERS; ++x){
System.out.println("Enter team members name >> ");
name = "CoolName";
teams[y].setMember(x, name);
}
}
x = 0;
y = 0;
for(y = 0; y < NUM_TEAMS; ++y){
System.out.println(x);
for(x = 0; x < NUM_TEAM_MEMBERS; ++x);{
System.out.println(x);
System.out.println("\nMembers of team " +
teams[y].getTeamName());
// We have an issue here!!!!!!
System.out.print(teams[y].getMember(x) + " ");
}
}
System.out.println();
}
}
答案 0 :(得分:0)
Suppose your for loop has wrong syntax and it should be like this.
for(y = 0; y < NUM_TEAMS; ++y){
System.out.println(x);
for(x = 0; x < NUM_TEAM_MEMBERS; ++x){
System.out.println(x);
System.out.println("\nMembers of team " +
teams[y].getTeamName());
// We have an issue here!!!!!!
System.out.print(teams[y].getMember(x) + " ");
}
}