gpt4 book ai didi

Java 抛出 InputMismatchException

转载 作者:行者123 更新时间:2023-11-30 07:26:35 27 4
gpt4 key购买 nike

我开始学习 Java,并且正在根据书本做一些练习。在执行此操作时,我遇到了以下错误:线程“main”java.util.InputMismatchException 中出现异常。我正在编写一个简单的程序,它从 .txt 文件中获取数据并将其返回到控制台。代码如下:

Employee.java:

import static java.lang.System.out;

public class Employee {
private String name;
private String jobTitle;

public void setName(String nameIn) {
name = nameIn;
}
public String getName() {
return name;
}

public void setJobTitle(String jobTitleIn) {
jobTitle = jobTitleIn;
}
public String getJobTitle() {
return jobTitle;
}

public void cutCheck(double amountPaid){
out.printf("Pay an employee %s ", name);
out.printf("(%s) ***$", jobTitle);
out.printf("%,.2f", amountPaid);
}
}

DoPayroll.java:

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

class DoPayroll {
public static void main(String[] args) throws IOException {
Scanner diskScanner = new Scanner(new File ("EmployeeInfo.txt"));
for(int empNum = 1; empNum <= 3; empNum++){
payOneEmployee(diskScanner);
}
}
static void payOneEmployee(Scanner aScanner) {
Employee anEmployee = new Employee();
anEmployee.setName(aScanner.nextLine());
anEmployee.setJobTitle(aScanner.nextLine());
anEmployee.cutCheck(aScanner.nextDouble());
aScanner.nextLine();
}
}

EmployeeInfo.txt:

John
Manager
15000.00
Alice
Secretary
8000.00
Bob
Engineer
12000.00
**an empty line**

编译器的错误日志:

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.nextDouble(Scanner.java:2413)
at DoPayroll.payOneEmployee(DoPayroll.java:19)
at DoPayroll.main(DoPayroll.java:11)

最佳答案

您的问题是由于 Scanner 使用当前的 Locale 来解析 Double 因此您需要显式设置 Locale 允许使用点作为小数点分隔符,例如 Locale.US 。因此,要修复您的代码,您只需在 for 循环之前将其添加到代码中即可:

diskScanner.useLocale(Locale.US);

关于Java 抛出 InputMismatchException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36750667/

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