我有我的程序从txt文件读取,然后将txt信息转换为汽车对象并将它们添加到数组列表中。从txt文件读取时的错误处理
try {
String filePath = "car.txt";
File f = new File(filePath);
Scanner sc = new Scanner(f);
List<Car> car = new ArrayList<Car>();
while(sc.hasNextLine()){
String newLine = sc.nextLine();
String[] details = newLine.split(" ");
String brand = details[0];
String model = details[1];
double cost = Double.parseDouble(details[2]);
Car c = new Car(brand, model, cost);
Car.add(c);
}
但是,如果txt文件中的一行不包含这三个组件,则它会崩溃。我将如何检查该行是否包含全部3个组件,如果不打印消息然后终止?
堆栈跟踪 -
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at Main.loadPerson(Main.java:31)
at Main.main(Main.java:12)
请出示访问元素之前的堆栈跟踪 – ItamarG3
检查'details'的'length',你可能会得到'ArrayIndexOutOfBoundsException' – Saravana