gpt4 book ai didi

java - 读取文件中的 int 时出现错误 NoSuchElementException

转载 作者:行者123 更新时间:2023-12-02 07:17:18 25 4
gpt4 key购买 nike

import java.util.*;
import java.io.*;

public class PayrollDemo{
public static void main(String[]args) throws FileNotFoundException {
Scanner input = new Scanner("Output.txt");
Employee employee = readEmployee(input); // <------ error here
input.useDelimiter("\t");
while(input.hasNext())
{
readEmployee(input);
printDetail(employee);
}
input.close();
}

public static Employee readEmployee(Scanner s)
{
String name = s.next();
int id = s.nextInt(); // <------ error here
double hourlyPayRate = s.nextDouble();
double hoursWorked = s.nextDouble();
Employee emp = new Employee(name, id);
emp.SethourlyPayRate(hourlyPayRate);
emp.SethoursWorked(hoursWorked);
return emp;
}

public static void printDetail(Employee e)
{
System.out.printf(e.getName()+ " " + e.getId()+ " " + e.GethourlyPayRate()+ " " + e.GethoursWorked()+ " " +e.GetGrossPay());
}
}

我的代码未从扫描仪读取 int 返回消息:NoSuchElementException。并且错误还指向 Employee 员工 readEmployee(input)。

最佳答案

在检查输入是否存在之前切勿读取输入。在使用 Scanner#nextXXX 之前使用 Scanner#hasNextXXX 方法。此外,每当您使用 Scanner.next()Scanner#nextIntScanner#nextDouble 方法时,都会留下一个换行符,未读取,因此您需要使用对 Scanner#next() 的空白调用来使用它。

因此,将 public static Employee readEmployee(Scanner s) 方法的前 4 行替换为:

// Use conditional operator to test for any available input. 
// If no input is available, just give a default from your side.
String name = s.hasNext() ? s.next() : "";
s.next();
int id = s.hasNextInt() ? s.nextInt(): 0; // <------ error here
s.next();
double hourlyPayRate = s.hasNextDouble() ? s.nextDouble(): 0.0;
s.next();
double hoursWorked = s.hasNextDouble() ? s.nextDouble(): 0.0;
s.next();

关于java - 读取文件中的 int 时出现错误 NoSuchElementException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14781482/

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