java - 输入文件不匹配异常

标签 java exception

我无法让我的代码读取名为 pets.txt 的文件。我检查了其他类似的问题,但似乎找不到解决方案。当我尝试读取一行时发生错误:

名称,1,1.2

此处的代码应输出 pets.txt 中找到的宠物的姓名、年龄和体重

 // import packages
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.io.FileReader;

public class Pets
{

    // throw exception if the file isn't found
    public static void main (String[] args) throws FileNotFoundException
    {
        // Create a scanner objcct to read the file
        Scanner fileReader = new Scanner(new FileReader("pets.txt"));

        // Initiate objects and variables 
        PetRecord firstPet = null;
        PetRecord pet = null;
        PetRecord smallestPet = null;
        PetRecord largestPet = null;
        PetRecord oldestPet = null;
        PetRecord youngestPet = null;
        double age = 0, weight = 0;
        int counter = 0;

        if(fileReader.hasNext())
        {
            // Create a reference to compare values
            firstPet = new PetRecord();
            // Create a delimiter to find the pet data
            fileReader.useDelimiter(",");
            // Call accessors to set name and age in the file
            firstPet.setName(fileReader.next());
            firstPet.setAge(fileReader.nextInt());
            // Set a delimiter to read the next line
            fileReader.useDelimiter("[,\n]");
            // set the weight using weight accessor
            firstPet.setWeight(fileReader.nextDouble());

            // Print firstPet info
            System.out.println(firstPet);
            // Use pet1 to set values to be compared
            smallestPet = firstPet;
            largestPet = firstPet;
            oldestPet = firstPet;
            youngestPet = firstPet;

            // Increment counter
            counter++;

            // Add firstPet to age and weight total
            age += firstPet.getAge();
            weight += firstPet.getWeight();
        }

        // A while loop to read until there are no more lines
        while(fileReader.hasNext())
        {
            // Ctreate a new pet and read the data with the fileReader and delimiter
            pet = new PetRecord();
            pet.setName(fileReader.next());
            fileReader.useDelimiter(",");
            pet.setAge(fileReader.nextInt());
            fileReader.useDelimiter("[,\n]");
            pet.setWeight(fileReader.nextDouble());

            // Print the pets info
            System.out.println(pet);

            // if statement to find largest and smallest pet
            if(pet.getWeight() < smallestPet.getWeight()) 
                smallestPet = pet;
            if(pet.getWeight() > largestPet.getWeight()) 
                largestPet = pet;
            // if statment to find oldest and youngest
            if(pet.getAge() > oldestPet.getAge())
                oldestPet = pet;
            if(pet.getAge() < youngestPet.getAge())
                youngestPet = pet;
            // demonstrate use of equals
            if(pet.equals(firstPet))
                System.out.println(pet + " is equal to " + firstPet);


            // inctrement counter for each pet, keeping track of total
            counter++;
            // add each pets age and weight to the total 
            age += pet.getAge();
            weight += pet.getWeight();
        }

        // divide the age and weight by the counter to find the average of each
        age /= counter;
        weight /= counter;

        // Print the data
        System.out.println();
        System.out.println("Smallest Pet:\t" + smallestPet);
        System.out.println("Largest Pet:\t" + largestPet);
        System.out.println("Youngest Pet:\t" + youngestPet);
        System.out.println("Oldest Pet:\t" + oldestPet);
        System.out.println("Average Age:\t" + age + " years");
        System.out.println("Average Weight:\t" + weight + "lb");


        fileReader.close();

    }

}

相反,我在文本文件的第一行收到输入不匹配异常。我正在读取一个 String、一个 int,然后读取一个 double,因此不确定哪里发生不匹配......我仔细检查以确保该文件保存在同一个项目文件夹中,并且确实如此。

编辑:错误如下:

exception java.util.fileInputMismatch at:
java.util.Scanner.throwFor(Unknown Source)
java.util.Scanner.next(Unknown Source)
java.util.Scanner.nextDouble(Unknown Source)
at Pets.Main(Pets.java:37)

编辑:这里是pets.txt

Barney,5,12.6
Frenchy,3,43.5
Marcus,4,54.2
Gilbert,12,4.6
Milley,2,7.4

最佳答案

作为快速修复,您可以代替 fileReader.nextDouble() -> Double.valueOf(fileReader.next())

我还没有弄清楚为什么会发生这种情况。我正在检查并将编辑我的答案。干杯!

稍后编辑:问题是由于扫描仪使用了错误的区域设置造成的。要解决您的问题,您在创建 Scanner 后所需要做的就是 fileReader.useLocale(Locale.US)

工作示例:

Scanner fileReader = new Scanner(new FileReader("pets.txt"));
    fileReader.useLocale(Locale.US);

    double age = 0, weight = 0;
    int counter = 0;

    // A while loop to read until there are no more lines
    while(fileReader.hasNext()) {
        fileReader.useDelimiter(",");
        System.out.println(fileReader.next());
        System.out.println(fileReader.nextInt());
        fileReader.useDelimiter(Pattern.compile("[\\r\\n,]+"));
        System.out.println(fileReader.nextDouble());

    }

    fileReader.close();

我的 pets.txt 文件正是您作为示例提供的文件。

希望对你有帮助!

关于java - 输入文件不匹配异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41108334/

相关文章:

java - 使用扫描仪输入和正/负数的“while”无限循环

java - 二叉搜索树,添加相同元素异常(exception)。

php - 是否有 PHP 的 linter 可以像 Java 一样显式显示所有异常?

java - 何时捕获异常(高级别与低级别)?

python - 使用cython从C++构造函数传播异常

java - 连接失败 : ECONNREFUSED

java - 服务器线程看不到序列化对象的更改字段

java - 如何获取 FaunaDB 类中的所有实例

java - Assertequals (double, double, delta) 问题

具有 ConcurrentModificationException 的 Java 线程