gpt4 book ai didi

java - 使用扫描仪读取文本文件结果为 'InputMismatchException'

转载 作者:行者123 更新时间:2023-12-01 09:42:13 25 4
gpt4 key购买 nike

我有文本文件,每一行都有人的日期(姓名、性别、年龄、体重)

David Smith
Male
32
85.83
Sarah Apple
Female
27
56.23
Teller Saimone
Male
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);
}

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

run:
David Smith
Male
32
85.83

Sarah Apple
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 PersonDrive.main(PersonDrive.java:36)
/home/jaguar/.cache/netbeans/8.1/executor-snippets/run.xml:53: Java returned: 1
BUILD FAILED (total time: 1 second)

似乎当它执行下一次读取的循环时,它读取了空格

最佳答案

将 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() 时,它返回第四行的其余部分,该行是空白的。使用我的解决方案,您可以获取整行,然后轻松地将其转换为整数或 double 。

关于java - 使用扫描仪读取文本文件结果为 'InputMismatchException',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38368613/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com