所以基本上我已经收到一个问题:
创建将读取members.txt文件内容的程序。成员必须分为3组,每组一个。处理完所有成员后,将有关每个团队有多少个成员以及什么是队长的信息输出到终端。文件值以逗号分隔,格式如下:
first_name,last_name,team_name,is_captain
这是我想到的代码(idk关于效率,因为我还很新):
package ssst.edu.ba;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner("members.txt");
int rcount = 0,bcount = 0,gcount = 0;
ArrayList<Student> red = new ArrayList<Student>(5);
ArrayList<Student> blue = new ArrayList<Student>(5);
ArrayList<Student> green = new ArrayList<Student>(5);
String line;
String rCap = "";
String bCap = "";
String gCap = "";
while ((line = scan.nextLine()) != null) {
String[] obj = line.split(",");
if(obj[2] == "Red") {
Student a = new Student(obj[0],obj[1],obj[2],Boolean.parseBoolean(obj[3]));
red.add(a);
rcount++;
if(obj[3] == "true") {
rCap = obj[0] + obj[1];
}
}
else if (obj[2] == "Blue") {
Student a = new Student(obj[0],Boolean.parseBoolean(obj[3]));
blue.add(a);
bcount++;
if(obj[3] == "true") {
bCap = obj[0] + obj[1];
}
}
else {
Student a = new Student(obj[0],Boolean.parseBoolean(obj[3]));
green.add(a);
gcount++;
if(obj[3] == "true") {
gCap = obj[0] + obj[1];
}
}
}
System.out.println("There are " + rcount + " people on the red team.");
System.out.println("There are " + bcount + " people on the blue team.");
System.out.println("There are " + gcount + " people on the green team.");
System.out.println("The captain for the red team is: " + rCap);
System.out.println("The captain for the blue team is: " + bCap);
System.out.println("The captain for the green team is: " + gCap);
}
}
“ Student”类很简单,它具有3个私有String属性和一个私有bool值,它还具有一个带有4个参数的构造函数,用于将值设置为文本文档“ members.txt”中给出的值
文本文档如下所示:
Ginny,Gullatt,Blue,false
Tiara,Curd,Red,false
Camie,Poorman,Green,false
Jammie,Hasson,false
Lionel,Hailey,false
Genevive,Mckell,true
Esteban,Slaubaugh,false
Elden,Harte,false
Tasia,Rodrigue,false
Nathanial,Dentler,false
Valda,Nicoletti,false
Kary,Wilkerson,false
Coletta,Akey,false
Wilmer,Jack,false
Loreta,Agnew,true
Suzy,Cleveland,false
Pasty,Laprade,false
Candie,Mehaffey,false
Glady,Landman,true
Tierra,Mckeown,false
问题:我收到此异常消息
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 1
我不知道这是绑定到ArrayList还是String数组“ obj”,我也不知道如何解决它。