0

我一直在寻找解决方案,但基本上发生的事情是我需要创建一个汽车数据库并从 csv 文件中导入值。当我尝试在 csv 文件中输入最后一个单元格时,它返回 0 和输入不匹配...这是我的代码

public void readFile(String fileName) throws Exception {
    File f = new File(fileName);
    Scanner sc = new Scanner(f);
    sc.useDelimiter(",");

    while (sc.hasNext() && i < cars.length) {
        try {

            model = sc.next();
            sc.useDelimiter(",");
            make = sc.next();
            sc.useDelimiter(",");
            mpg = sc.nextDouble();
            sc.useDelimiter(",");
            weight = sc.nextInt();
            sc.useDelimiter(",");
            year = sc.nextInt();

        } catch (InputMismatchException e) {
            System.out.println("try again");
        }

        cars[i] = new Car(model, make, mpg, weight, year);

        // System.out.println(cars[i].toString());
        i++;

输出:

Welcome to the Car Database!
Enter the size of the array:
    5
Enter the name of the input file:
    cardb.csv
    try again
    try again
    try again
    try again
    try again
Enter make, mpg, weight, all, or quit:
    all
    Model:chevelle malibu Make:chevrolet mpg:18.0 weight:3504 year:0
    Model:70
    skylark 320 Make:buick mpg:15.0 weight:3693 year:0
    Model:70
    satellite Make:plymouth mpg:18.0 weight:3436 year:0
    Model:70
    rebel sst Make:amc mpg:16.0 weight:3433 year:0
    Model:70
    torino Make:ford mpg:17.0 weight:3449 year:0

基本上,年份应该说 70 而不是 0,但它正在读取它作为下一行的模型......这是 cardb.csv文件

一些输入:

chevelle malibu,chevrolet,18,3504,70
skylark 320,buick,15,3693,70
satellite,plymouth,18,3436,70
rebel sst,amc,16,3433,70
torino,ford,17,3449,70
galaxie 500,ford,15,4341,70
impala,chevrolet,14,4354,70
fury iii,plymouth,14,4312,70
catalina,pontiac,14,4425,70
ambassador dpl,amc,15,3850,70
challenger se,dodge,15,3563,70
'cuda 340,plymouth,14,3609,70

这是例外,

Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:864)
    at java.util.Scanner.next(Scanner.java:1485)
    at java.util.Scanner.nextInt(Scanner.java:2117)
    at java.util.Scanner.nextInt(Scanner.java:2076)
    at csc212hw04.CarDatabase.readFile(CarDatabase.java:58)
    at csc212hw04.Main.main(Main.java:47)
    C:\Users\Dan1\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
    BUILD FAILED (total time: 9 seconds)
4

0 回答 0