gpt4 book ai didi

java - 从文件读取,InputMismatchException

转载 作者:行者123 更新时间:2023-12-01 14:06:49 25 4
gpt4 key购买 nike

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

File file = new File("data.txt"); // select file
try{
Scanner sc = new Scanner(file); // set scanner to file
try{
while (sc.hasNextLine()){
Employee employee = new Employee(); //create employee to hold data
assignData(sc); //read data into employee
employee.getGross(); //calculate gross pay
addEmployee(employee);//assign employee to array
}//end while
}//end try2
finally {
sc.close(); // close file, saving resource usage
}//end finally
}//end try1
catch(IOException e) {
e.printStackTrace();
}

public static void assignData(Scanner input){
//accept scanner
//read necessary input for employee
EmpID = input.next();****
LastName = input.next();****
FirstName = input.next();****
(LINE 36)Hours = input.nextDouble();
Rate = input.nextDouble();
}

数据文件内容

42345 Bruch Max 40 21.50 
23456 Elgar Eddie 43 20.0
34567 Bach John 30 30
12345 Wagner Rick 41 30
88888 Mozart Wolfie 36 40
65432 Chopin Fred 45 23.25
72345 Strauss Butch 50 25
<小时/>

编译,出现错误

"Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextDouble(Scanner.java:2456)
at programassignment1c.Employee.assignData(Employee.java:36) (
at programassignment1c.ProgramAssignment1C.main(ProgramAssignment1C.java:44)

Java 结果:1

<小时/>

Employee 类中的第 36 行,在上面突出显示,它是 nextDouble() 我做错了什么?即使 double 没有小数位,也可以扫描它们吗?

用手写出来,我看到扫描仪从 42345 开始,并将其设置为 EmpID,然后扫描仪前进到空格

Bruch 并将其设置为 LastName,然后扫描仪将空格前进到 Max,并将其设置为 FirstName,然后扫描仪将空格前进到 40,并应将其设置为 Hours???我没有正确跟随扫描仪?

最佳答案

我相信您需要在这里使用特定的数据类型方法:

    EmpID = input.nextLine();
LastName = input.nextLine();
FirstName = input.nextLine();

尝试使用 nextInt/next 而不是 nextLine。因为 nextLine 会读取整行,当您尝试将其分配给 int 值,它抛出 InputMismatchException

关于java - 从文件读取,InputMismatchException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18836819/

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