0
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());
    }
}

我的代码没有从 Scanner 中读取 int,而是返回一条消息:NoSuchElementException。并且错误还指向Employee员工readEmployee(输入)。

4

2 回答 2

1

执行时您的文件中似乎没有任何可用元素s.nextInt()

当您next()调用时Scanner,最好使用 . 检查元素是否可用hasNext()

例子:

if(s.hasNextInt())   //while (or) if or whatever you want to use.
{
 int id = s.nextInt(); 
}
于 2013-02-08T21:16:20.233 回答
1

在检查输入是否存在之前,切勿读取它。使用Scanner#hasNextXXX前使用方法Scanner#nextXXX。此外,每当您使用Scanner.next(), or Scanner#nextIntorScanner#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();
于 2013-02-08T21:18:10.040 回答