我在while循环中的第二个while循环中不断获得java.lang.ArrayIndexOutOfBoundsException
。我缺少一步吗?我正在从文件中读取我的信息。该计划的整个目标是让我做以下事情:
课程资料中提供了示例文件。
格式如下,在具有多个值的行上使用制表符分隔条目:
QB< - 职位/角色
1 A. Rodgers GB< - 价值,名称,团队/创作者
2 T. Brady NE
3 D. Brees没有
-----< - 5个连字符表示文件即将切换到新的位置/角色
RB< - 下一个职位/角色
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.TreeMap;
public class Superhero {
static TreeMap<String, ArrayList<Player>> positions = new TreeMap<String, ArrayList<Player>>();
ArrayList<String> team = new ArrayList<String>();
public static void main(String[] args) throws IOException {
int teams = 0;
String fileName = "";
Scanner input = new Scanner(System.in);
System.out.print("Whats the name of the file: ");
fileName = input.next();
File superHeroFile = new File(fileName);
Scanner file = new Scanner(superHeroFile);
while (file.hasNextLine()){
//read the position
String role = file.nextLine();
// ready to create the ArrayList for all players in this role
ArrayList<Player> playersInRole = new ArrayList<Player>();
positions.put(role , playersInRole);
// until I read "-----" I have a new all players in this current position
String possiblePlayer = file.next();
while (!possiblePlayer.equals("-----")){
String[] playerParts = possiblePlayer.split("\t");
String ranking = playerParts[0];
String name = playerParts[1];
String originalTeam = playerParts[2];
}
}
for(int buildTheTeam = 0; buildTheTeam < teams; buildTheTeam++){
int playerType = input.nextInt();
switch (playerType){
case 1: //Leader
break;
case 2: //Brawn
break;
case 3: //Gadgets
break;
case 4: //Female Influence
break;
case 5: //Bad Guy
break;
}
}
while (file.hasNextLine()){
String wholeFile = file.nextLine();
System.out.println(wholeFile);
}
//get the number of teams
System.out.print("How many teams will you have? ");
teams = input.nextInt();
input.nextLine();
for(int teamName = 0; teamName < teams; teamName++){
System.out.print("What is the name of your team? ");
String TeamName = input.next();
System.out.println("Team " + TeamName );
}
}
}
感谢您的帮助谢谢!
答案 0 :(得分:0)
致电
possiblePlayer.split("\t");
你得到的结果不到3个。
你确定这些字段是用标签分隔的吗?
您可以插入以下行来确定实际的内容。
String[] playerParts = possiblePlayer.split("\t");
System.out.println("possiblePlayer: " + possiblePlayer);
System.out.println("num fields: " + playerParts.length);
答案 1 :(得分:0)
这一行:
String[] playerParts = possiblePlayer.split("\t");
无法按预期工作,因为在某些时候possiblePlayer
的标签少于3个(\t
)
在访问之前,您必须检查数组playerParts
是否具有所需数量的元素,
用户playerParts.length
获取数组的元素编号。