I’m able to read everything from the text file and print the data yet I get a “No Such Element” Exception. All the solutions i’ve found say to use “HasNext” in while loop and yet it doesn’t seem to work for me
public void fileReader() throws 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,Toyota,Yaris,Sedan,2012,4,Blue,50,15,10,10 C002,Toyota,Corolla,Hatch,2020,4,White,45,20,10,10 C003,Toyota,Kluger,SUV,2019,7,Grey,70,20,20,10 C004,Audi,A3,Sedan,2015,5,Red,65,10,20,10 C005,Holden,Cruze,Hatch,2020,4,Green,70,10,10,10 C006,BMW,X5,SUV,2018,7,White,100,25,20,10 C007,BMW,320i,Sedan,2021,5,Grey,75,10,15,N/A C008,Ford,Focus,Sedan,2014,5,Red,45,10,10,N/A C009,Ford,Puma,SUV,2015,5,Black,70,20,15,20
This is the Exception I get:
Advertisement
Answer
- your CSV has actually two delimiters: comma and new line. Try:
scan.useDelimiter(",|\R");
- discount is read twice for numeric values, try:
String discountStr = scan.next(); discount = discountStr.equals("N/A") ? 0 : Double.parseDouble(discountStr);