【问题标题】:Getting an error from save to file : Exception in thread "main" java.util.InputMismatchException从保存到文件中出现错误:线程“主”java.util.InputMismatchException 中的异常
【发布时间】:2019-03-28 18:41:18
【问题描述】:

我在尝试运行此程序时遇到错误(编辑和删除 csv 文件中的内容)。 错误:

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.nextDouble(Scanner.java:2413)
    at project.AnimalManager.loadFromFile(AnimalManager.java:88)
    at project.Test.main(Test.java:10)

主应用

package project;


public class Test {

    public static void main(String[] ages) {

        //Load file 
        AnimalManager aMgr = new AnimalManager();
        aMgr.loadFromFile("AnimalDetails.txt");

//        try {
//        Animals anim = aMgr.getAnimalById("48331827032019");
//        aMgr.deleteAnimal(anim);
//        } catch (IllegalArgumentException exc) {
//          System.out.println(exc);
//      }

        System.out.println("Edit Animal:");

        boolean edited = aMgr.editAnimal("48331827032019",5,"German","200","Huskies","Huskies","n","n",1000.0,"John"); //By ID
            if (edited) {
                System.out.println("Animal has been edited successfully.");
            } else {
                System.out.println("Animal not found (test failed).");

            }
}
}

动物管理员

package project;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;





public class AnimalManager {

    private final ArrayList<Animals> animalList;

    public AnimalManager() {
        this.animalList = new ArrayList<>();
    }

    public boolean addAnimal(Animals a) {
        if (a == null)
            throw new IllegalArgumentException("Animal argument is null");

        if(animalList.contains(a))
            return false;
        animalList.add(a);
        return true;
    }

    public void deleteAnimal (Animals a) {
        if (a == null)
            throw new IllegalArgumentException("Animal argument is null");

        animalList.remove(a);
    }

    public Animals getAnimalById(String ID) {
        for (Animals a : this.animalList) {
            if (a.getID().equals(ID))
                return a; 
        }
        return null;
    }

    public boolean editAnimal(String ID, int age, 
            String breed, String breedPurity, String motherBreed, String fatherBreed, String medicalHistory, String identification, double price, String owner) {
        // test for null and for duplicate
        if (ID == null || age == 0 || breed == null || breedPurity == null || motherBreed == null|| fatherBreed == null || medicalHistory == null|| price == 0 || owner == null)
            throw new IllegalArgumentException("One or more arguments are null");

        // Search for the animal.
        for (Animals p: animalList) {
            if (p.getID().equals(ID)) {
                p.setAge(age);
                p.setBreed(breed);
                p.setMother(motherBreed);
                p.setFather(fatherBreed);
                p.setMedical(medicalHistory);
                p.setIdenti(identification);
                p.setPrice(price);
                p.setOwner(owner);
                return true; // Animal has been edited successfully.
            }
        }
        return false; // Means animal with the supplied id is not found.
    }


    //Load from file
    public void loadFromFile(String filename) {
        try {
            Scanner sc = new Scanner(new File(filename));

            sc.useDelimiter("[,\r\n]+");
            //animal details: id,age,breed,purity of breed,mother breed,father breed,medical history, identification, price, owner

            while(sc.hasNext()) {
                String ID = sc.next();
                int age = sc.nextInt();
                String breed = sc.next();
                String breedPurity = sc.next();
                String motherBreed = sc.next();
                String fatherBreed = sc.next();
                String medicalHistory = sc.next();
                String identification = sc.next();
                double price = sc.nextDouble();
                String owner = sc.next();

                animalList.add(new Animals(ID, age, breed, breedPurity, motherBreed, fatherBreed, medicalHistory, identification, price, owner ));

            }
            sc.close();

        }catch (IOException e) {
            System.out.println("Exception thrown. " + e);
    }


}

    public void saveToFile(String filename) {

        StringBuilder output = new StringBuilder(); // To store all passengers info.

        for (Animals p : animalList) { // Loop through the passengers to store
            // every passenger as the line of strings to add them to the file.
            output.append(p.getID()).append(",").append(p.getAge()).append(",").append(p.getBreed()).append(",")
                    .append(p.getMother()).append(",").append(p.getFather()).append(",").append(p.getMedical()).append(",")
                    .append(p.getIdenti()).append(",").append(p.getPrice()).append(",").append(p.getOwner()).append("\r\n");
        }

        try (FileWriter fw = new FileWriter(new File(filename))) {
            fw.write(output.toString());
        } catch (Exception e) {
            System.out.println("Passengers cannot be saved: " + e);
        }

    }

    public String toString() {
        // use String if more comfortable with it - StringBuilding faster for concat
        // than (immutable) String
        StringBuilder strBuilder = new StringBuilder();
        for (Animals p : this.animalList) {
            strBuilder.append(p.toString()).append("\n");
        }

        return strBuilder.toString();
    }
}

这里的想法是提供您要编辑的特定动物 ID,并写下新信息以替换旧信息。我已经有了保存到文件的方法,我认为这就是问题所在。

CSV

0,2,AmercianShorthair,100,AmercianShorthair,AmercianShorthair,y,y,900.0,Ann
3,4,GermanShepherd,100,GermanShepherd,GermanShepherd,no,yes,600.0,Dave
6,3,Poodle,100,Poodle,Poodle,yes,no,300.0,Dianna
456,4,Azawakh,50,Unknown,Azawakh,no,no,300.0,April
25041019042018,1,Vizsla,50,Vizsla,TreeingTennesseeBrindle,no,yes,500.0,Lex
3271,1,Beagle,50,Beagle,Unknown,no,no,200.0,Blanton
48331827032019,33,sheperd,50,50,50,no,yes,300.0,Mike

【问题讨论】:

  • Animal 中的第 88 行在哪里
  • double price = sc.nextDouble();
  • 当您的应用程序的输入数据不符合其规范时,您会收到此异常。您需要查看输入数据并进行修复。
  • 而不是 double price = sc.nextDouble(),做 String price = sc.next();并在之后立即打印。所以你可以看到它是什么。
  • 将价格类型更改为字符串?

标签: java


【解决方案1】:

CSV 应在末尾包含逗号,如下所示:

0,2,AmercianShorthair,100,AmercianShorthair,AmercianShorthair,y,y,900.0,Ann,
3,4,GermanShepherd,100,GermanShepherd,GermanShepherd,no,yes,600.0,Dave,
6,3,Poodle,100,Poodle,Poodle,yes,no,300.0,Dianna,
456,4,Azawakh,50,Unknown,Azawakh,no,no,300.0,April,
25041019042018,1,Vizsla,50,Vizsla,TreeingTennesseeBrindle,no,yes,500.0,Lex,
3271,1,Beagle,50,Beagle,Unknown,no,no,200.0,Blanton,
48331827032019,33,sheperd,50,50,50,no,yes,300.0,Mike

注意行尾的逗号。发生了什么,它是否会立即进入下一行并将名称与开头的数字结合起来。例如,“Ann3,4”,因为在这种情况下,换行符不是分隔符。

同样在 CSV 中,您拼错了 Shepherd。

由于分隔符不是换行符,所以它是这样的:

0,2,AmercianShorthair,100,AmercianShorthair,AmercianShorthair,y,y,900.0,Ann3,4,GermanShepherd,100,GermanShepherd,GermanShepherd,no,yes,600.0,Dave6,3,Poodle,100,Poodle,Poodle,yes,no,300.0,Dianna456,4,Azawakh,50,Unknown,Azawakh,no,no,300.0,April25041019042018,1,Vizsla,50,Vizsla,TreeingTennesseeBrindle,no,yes,500.0,Lex3271,1,Beagle,50,Beagle,Unknown,no,no,200.0,Blanton48331827032019,33,sheperd,50,50,50,no,yes,300.0,Mike

请注意它是如何表示 900.0、Ann3、4 等的。它会将它们全部移动一格,因此您实际上并没有将 600.0 读取为双精度,而是将 Dave 读取为双精度。

像这样编辑代码:

      for (Animals p : animalList) { // Loop through the passengers to store
            // every passenger as the line of strings to add them to the file.
            output.append(p.getID()).append(",").append(p.getAge()).append(",").append(p.getBreed()).append(",")
                    .append(p.getMother()).append(",").append(p.getFather()).append(",").append(p.getMedical()).append(",")
                    .append(p.getIdenti()).append(",").append(p.getPrice()).append(",").append(p.getOwner()).append(",").append("\r\n"); //add another append between getOwner and \r\n
        }

请注意,这是您将动物添加到 CSV 的位置。在这里,对于每一种动物,您现在也在每行的末尾附加一个逗号。 ed 在附加 getOwner 和附加 \r\n 之间。

【讨论】:

  • 为什么每行末尾都需要逗号?
  • 因为没有为回车或换行设置分隔符。你不是把它读成线条。好像都在一条线上。
  • 嗯,我该怎么办?
  • 我删除了 csv 文件的内容并用新的内容再次填充它,程序确实可以工作。但是,当我尝试再次运行它时,发生了同样的错误
  • 我像你说的那样编辑了代码和 CSV 文件,但仍然没有成功。
【解决方案2】:

@JustAFellowCoder 已告诉您解决问题的方法,但我认为使用 CVS 文件不是最好的主意。

使用java.util.Properties怎么样? 它非常简单,可以解决您的所有问题,您只需执行以下操作:

//Your file path
    Path path = Paths.get("Animal.properties");

    //Create a new properties and store it in a file
    Properties properties = new Properties();
    //your id
    int id = 1;
    //Everything in properties must be saved as Strings
    properties.setProperty("Id", String.valueOf(id));
    properties.store(Files.newOutputStream(path), null);

    //new properties
    properties = new Properties();
    properties.load(Files.newInputStream(path));
    System.out.println("Id: " + properties.getProperty("Id"));

您将获得一个可以轻松恢复的“Animal.properties”文件和一个打印“Id:1”的控制台。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-23
    • 2023-04-09
    相关资源
    最近更新 更多