我正在尝试读取Java中逗号分隔的文件,将行分配给String []数组,然后解析元素。但是,当我运行程序时,会得到ArrayIndexOutOfBounds异常,因为这是说我的数组大小为1(实际上一行有7个字段)。
这是我正在引用的代码部分:
public ApplianceList(int numAppliances, String fileName) throws IOException{
applianceList=new ArrayList<Appliance>(numAppliances);
File file=new File(fileName);
Scanner scan=new Scanner(file);
Random random=new Random();
Appliance a1;
while(scan.hasNext()) {
String [] fields=scan.nextLine().split(",");
if(fields[5]=="true") { //if it is a SmartAppliance
double onW=(double)Integer.parseInt(fields[2]);
double offW=(double)Integer.parseInt(fields[3]);
double percent=(double)Integer.parseInt(fields[6]);
a1=new SmartAppliance(onW,offW,percent);
}
错误专门针对if语句,说“索引5超出大小1的范围”
我查阅了许多其他文章来解决此问题,但是我的代码与人们所说的相符。我不确定自己在做什么错。
下面是正在读取的.txt文件中的示例:
10000001,Television - 36 inch,133,5,0.167,false,0.0
10000001,Bug Killer,40,0,0.5,false,0.0
10000001,Range - Large Surface Unit,2400,0,0.01,false,0.0
10000001,Lighting - Halogen,90,0,0.33,false,0.0
问题是由于以下代码块:
while(scan.hasNext()) {
String [] fields=scan.nextLine().split(",");
替换为
while(scan.hasNextLine()) {
String [] fields=scan.nextLine().split(",");