【问题标题】:InputFile Mismatch Exception输入文件不匹配异常
【发布时间】:2016-12-12 19:42:48
【问题描述】:

我无法让我的代码读取名为 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();

    }

}

相反,我在文本文件的第一行收到输入不匹配异常。我正在读取一个字符串、一个 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

【问题讨论】:

  • 你在调用nextDouble()时遇到不匹配的问题吗?

标签: java exception


【解决方案1】:

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

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

稍后编辑:问题是由于Scanner 使用了错误的语言环境。要解决您的问题,您在创建 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 文件正是你举的例子。

希望对你有帮助!

【讨论】:

  • 好吧,我刚才确实添加了语言环境,但它仍然给我同样的错误:(虽然这是个好主意
  • 编辑了我的答案。问题是我只尝试在 pets.txt 中使用一行。当我输入多行时,useDelimiter() 中定义的模式出现问题。将其更新为Pattern.compile("[\\r\\n,]+"),一切都按预期工作。干杯!
  • 感谢您的帮助!虽然这是一个入门的 java 类,但我认为我们还没有学习 Pattern 类。这个答案虽然有效......我如何在这里接受答案(对不起,stackoverflow的超级新手)
  • 答案左侧有一个复选标记,您必须打勾。你可以在这里阅读更多:meta.stackexchange.com/questions/5234/…
  • 其实,如果你不想使用Pattern,你可以直接使用useDelimiter("[\r\n,]+")。应该可以,但尚未测试。
猜你喜欢
  • 1970-01-01
  • 2013-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-13
  • 2012-07-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多