gpt4 book ai didi

java - 使用扫描仪读取文件时线程 "main"java.util.InputMismatchException 中出现异常

转载 作者:行者123 更新时间:2023-12-02 08:47:11 25 4
gpt4 key购买 nike

我正在尝试从文本文档中读取数据,格式如下:

123 Fluffy      12/04/2017  34  2   
124 Domino 11/23/2018 12 1
125 Rover 9/8/2018 45 10

它应该输出如下:

ID No. 123 : Fluffy : 2 years old : 34lbs 
Registered on 12/04/2017
ID No. 124 : Domino : 1 years old : 12lbs
Registered on 11/23/2018
ID No. 125 : Rover : 10 years old : 45lbs
Registered on 9/8/2018

但是,执行此操作时,它会输出以下错误:

Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at DogRunner1.main(DogRunner1.java:56)

该对象的代码如下所示:

public class Dog1
{

String name;

int age;
// regDate -- registration date (in the format: "YYYY/MM/DD")
String regDate;
int weight;
int idNumber;


public String bark() {
return "bark";
}

public void setAge(int a) {
age = a;
}

public void setRegDate(String b) {
regDate = b;
}
public void setId(int c) {
idNumber = c;
}
public void setWeight(int d) {
weight = d;
}

public String toString()
{
return "ID No. " + idNumber + " : " + name + " : " + age + " years old : " + weight +"lbs \nRegistered on " + regDate;
}
}

运行它的程序的代码如下所示:

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

public class DogRunner1
{


public static void main(String[] args) throws FileNotFoundException
{


Dog1 d3;
d3 = new Dog1();

File text = new File ("dogdata.txt");
Scanner inFile = new Scanner(text);
while(inFile.hasNext()) {
d3.setId(inFile.nextInt());
d3.name = inFile.nextLine();
inFile.nextLine();
d3.setRegDate(inFile.nextLine());
d3.setWeight(inFile.nextInt());
d3.setAge(inFile.nextInt());
System.out.println(d3);
inFile.nextLine();
}
inFile.close();
}
}

我知道你必须在两个字符串之间跳过一行,或者至少我认为这就是我的想法,并且我尝试了许多 nextLine() 放置的组合,但无济于事。我不知道出了什么问题,请帮忙。

最佳答案

您正在使用 nextLine() 读取名称和 regDate 字段。该方法读取该行的其余部分。您不希望这样,您只想读取单个单词,因此您应该使用 next():

    d3.setId(inFile.nextInt());
d3.name = inFile.next();
d3.setRegDate(inFile.next());
d3.setWeight(inFile.nextInt());
d3.setAge(inFile.nextInt());
System.out.println(d3);

关于java - 使用扫描仪读取文件时线程 "main"java.util.InputMismatchException 中出现异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61001976/

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