使用Scanner读取文本文件会导致'InputMismatchException'

时间:2016-07-14 07:58:58

标签: java java.util.scanner

我的文字文件中包含人的每一行日期(姓名,性别,年龄,体重)

  大卫史密斯   男
  32个
  85.83
  莎拉苹果
  女
  27个
  56.23
  Teller Saimone
  男
  29个
  87.71

这是我的代码:

Scanner inputFile = new Scanner(myFile);
while (inputFile.hasNext()) {
    Persone Pers = new Persone();
    Pers.setVehicleMake(inputFile.nextLine());
    System.out.println(Pers.getVehicleMake());
    Pers.setVehicleModel(inputFile.nextLine());
    System.out.println(Pers.getVehicleModel());
    Pers.setNumberCylinders(inputFile.nextInt());
    System.out.println(Pers.getNumberCylinders());
    Pers.setEstMPG(inputFile.nextDouble());
    System.out.println(Pers.getEstMPG());
    auotList.add(Pers);
}

当我运行代码时出现此错误:

  

运行:
  大卫史密斯   男
  32个
  85.83

     莎拉苹果   线程“main”中的异常java.util.InputMismatchException
  在java.util.Scanner.throwFor(Scanner.java:864)
  在java.util.Scanner.next(Scanner.java:1485)
  在java.util.Scanner.nextInt(Scanner.java:2117)
  在java.util.Scanner.nextInt(Scanner.java:2076)
  在PersonDrive.main(PersonDrive.java:36)
  /home/jaguar/.cache/netbeans/8.1/executor-snippets/run.xml:53:Java返回:1
  建筑失败(总时间:1秒)

当它为下一次读取做循环时,它似乎读取了空白

1 个答案:

答案 0 :(得分:1)

将parseInt()和parseDouble()方法与nextLine()方法结合使用将解决您的问题。我写了一些代码:

public class Person{
    private String name;
    private String gender;
    private int age;
    private double weight;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getGender() {
        return gender;
    }
    public void setGender(String gender) {
        this.gender = gender;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public double getWeight() {
        return weight;
    }
    public void setWeight(double weight) {
        this.weight = weight;
    }

}

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;

public class PersonTest {   
    public static void main(String[] args) throws FileNotFoundException {
        File inputFile = new File("data.txt");
        Scanner sc = new Scanner(inputFile);

        ArrayList<Person> peopleList = new ArrayList<Person>();
        Person p;

        while (sc.hasNext()){
            p = new Person();
            p.setName(sc.nextLine());
            System.out.println(p.getName());
            p.setGender(sc.nextLine());
            System.out.println(p.getGender());
            p.setAge(Integer.parseInt(sc.nextLine()));
            System.out.println(p.getAge());
            p.setWeight(Double.parseDouble(sc.nextLine()));
            System.out.println(p.getWeight());
            peopleList.add(p);
        }

        sc.close();
    }
}

我认为你的代码无法正常工作的问题是,在nextDouble()找到85.83之后,扫描程序跳过了这个数字并仍然在第4行。当您在第二个循环中调用nextLine()时,它返回第4行的其余部分,该行为空白。 使用我的解决方案,您可以采用一整行,然后轻松将其转换为整数或双数。