我收到错误java.lang.ArrayIndexOutOfBoundsException错误if语句
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 28
at assignment.assgn1.main(assgn1.java:44)
我将不胜感激,如果有人可以指出错误
package assignment;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import com.opencsv.CSVReader;
import java.io.FileNotFoundException;
public class assgn1 {
public static void main(String[] args) throws IOException
{
try{
CSVReader csvReader = new CSVReader(new FileReader("E:/AviationData.txt"),'\t','\n');
PrintWriter NYreports = new PrintWriter("E:/NYReports.txt");
String [] nextLine;
int x;
int sum=0;
double totalFatal=0;
Integer largest = 0;
Integer smallest = 0;
String [] token = null;
//read first line, but it will not be counted with the rest of the records
nextLine = csvReader.readNext();
//create a map for unique Broad Phase in flight fields
Map<String, Integer> broadPhase = new HashMap <String, Integer>();
//create an array list that will take in integer values of Fatal Injuries
ArrayList <Integer> intList = new ArrayList<Integer>();
while ((nextLine = csvReader.readNext()) !=null){
sum++;
String field = nextLine[0];
//using regex values!
token = field.split("\\s\\|\\s");
//for (String s: token){
//System.out.println(s);
//}
if(token[28].equals(" ")){
broadPhase.put(token[28],0);
}
if(!token[28].equals(" ") && !token[28].equals("")){
broadPhase.put(token[28], 1);
}
//search for Fatal Injury values
if(!token[23].isEmpty()){
x=Integer.parseInt(token[23]);
//add to ArrayList
intList.add(x);
totalFatal = x + totalFatal;
}
if(token[4].contains(", NY") && token[5].contains("/2015")){
NYreports.println(nextLine[0]);
}
}
for(int i =0; i<intList.size()-1; i++){
if (intList.get(i) > largest);
largest = intList.get(i);
if (intList.get(i)< smallest)
smallest = intList.get(i);
}
System.out.println("There are " + sum + " records");
System.out.println("There are " + (broadPhase.size())+" unique values in Broad Phase of Flight");
totalFatal = (totalFatal/sum);
System.out.println(largest + " is the largest number of Fatal injuries");
System.out.println("The average of Fatal injuries is " + totalFatal);
NYreports.close();
csvReader.close();
}
catch (FileNotFoundException ex){
System.out.println("File not Found");
}
}
}
错误是在行if(token [28] .equals(“”)){。写入。 我可以改变什么来避免它。如果我使用的方法有任何改变,也可以完成。
它只是意味着在'token'阵列的第29项不存在。请记住,在访问数组中的某个索引之前,数组索引从0开始为 – Jyr
做一个长度检查 –