【发布时间】:2022-10-06 15:21:05
【问题描述】:
我能够从文本文件中读取所有内容并打印数据,但我得到一个“没有这样的元素”异常。我发现的所有解决方案都说在 while 循环中使用“HasNext”,但它似乎对我不起作用
public void fileReader() 抛出 IOException {
String id;
String brand;
int yearOfManufacture;
int numSeats;
double rentalPerDay;
double insurancePerDay;
double serviceFee;
double discount;
String model;
String type;
String color;
ArrayList<Vehicle> vehicleArray = new ArrayList<>();
File file = new File(\"C:/Users/jockg/Downloads/Fleet (1).csv\");
Scanner scan = new Scanner(file);
scan.useDelimiter(\"n/n\");
while (scan.hasNext() || scan.hasNextDouble() || scan.hasNextInt()) {
id = scan.next();
System.out.println(id);
brand = scan.next();
System.out.println(brand);
model = scan.next();
System.out.println(model);
type = scan.next();
System.out.println(type);
yearOfManufacture = Integer.parseInt(scan.next());
System.out.println(yearOfManufacture);
numSeats = Integer.parseInt(scan.next());
System.out.println(numSeats);
color = scan.next();
System.out.println(color);
rentalPerDay = Double.parseDouble(scan.next());
System.out.println(rentalPerDay);
insurancePerDay = Double.parseDouble(scan.next());
System.out.println(insurancePerDay);
serviceFee = Double.parseDouble(scan.next());
System.out.println(serviceFee);
if (scan.next().equals(\"N/A\")) {
discount = 0;
} else {
discount = Double.parseDouble(scan.next());
}
System.out.println(discount);
Car newCar = new Car(id, brand, yearOfManufacture, numSeats, rentalPerDay, insurancePerDay, serviceFee,
discount, model, type, color);
vehicleArray.add(newCar);
}
}
C001,丰田,雅力士,轿车,2012,4,蓝色,50,15,10,10 C002,丰田,卡罗拉,哈奇,2020,4,白色,45,20,10,10 C003,丰田,克鲁格,SUV,2019,7,灰色,70,20,20,10 C004,奥迪,A3,轿车,2015,5,红色,65,10,20,10 C005,霍顿,科鲁兹,哈奇,2020,4,绿色,70,10,10,10 C006,宝马,X5,SUV,2018,7,白色,100,25,20,10 C007,宝马,320i,轿车,2021,5,灰色,75,10,15,N/A C008,福特,福克斯,轿车,2014,5,红色,45,10,10,N/A C009,福特,彪马,SUV,2015,5,黑色,70,20,15,20
这是我得到的例外:
-
在检查一次
scan.hasNext()之后,您将调用scan.next()十次,因此如果任何行没有所需的字段数,您将收到错误消息。也许使用 CSV 解析库。 -
您可能还需要解释分隔符 (
n/n) - 您是否打算在换行符上进行分隔?
标签: java io nosuchelementexception