读取数据,操作数据并输出数据时出错

时间:2011-10-06 21:30:33

标签: coding-style

问题已完成且无法删除帖子。

1 个答案:

答案 0 :(得分:2)

我猜这是因为你有:

 while (inputFile.hasNext())

使用 Scanner.hasNextLine

修改

我用您的示例输入测试了您的代码。我明白你的意思了。

while ( inputFile.hasNextLine() ) {
            employeeID = inputFile.nextLine(); // Read info from first line and store it in employeeID
            employeeName = inputFile.nextLine(); // Read info from next line and store it in employeeName

            userInput = JOptionPane.showInputDialog( "Employee Name: " + employeeName + "\nEnter number of" + // display employee name and ask for number of hours worked
            " hours worked:" );

            hours = Double.parseDouble( userInput ); // Store user's parsed input into hours
            wageRate = inputFile.nextDouble(); // Read info from next line and store it in wageRate
            taxRate = inputFile.nextDouble(); // Read info from next line and store it in taxRate

使用 hasNextLine 作为条件只会确保对 nextLine 的下一次调用有效。但是,您调用 nextLine 两次,然后再调用 nextDouble 。您可以(1)确保您所做的调用与文件完全匹配,或者(2)每次调用 next 时检查是否有下一个令牌。我认为(1)是你的问题。

我能够使用以下内容修复您的程序:

while ( inputFile.hasNextLine() ) {
    employeeID = inputFile.nextLine();
    employeeName = inputFile.nextLine();
    userInput = JOptionPane.showInputDialog( "Employee Name: " + employeeName + "\nEnter number of hours worked:" );
    hours = Double.parseDouble( userInput );
    wageRate = Double.parseDouble(inputFile.nextLine());
    taxRate = Double.parseDouble(inputFile.nextLine());
    Paycheck paycheck = new Paycheck( employeeID, employeeName, wageRate, taxRate, hours );
    paycheck.calcWages();
    JOptionPane.showMessageDialog( null, "Employee ID: " + 
            paycheck.getEmployeeID() + "\nName: " + 
            paycheck.getEmployeeName() + "\nHours Worked: " + 
            hours + "\nWage Rate: $" + 
            money.format( paycheck.getWageRate() ) + "\nGross Pay: $" + 
            money.format( paycheck.getGrossPay() ) + "\nTax Rate: " + 
            paycheck.getTaxRate() + "\nTax Withheld: $" + 
            money.format( paycheck.getTaxWithheld() ) + "\nNet Pay: $" + 
            money.format( paycheck.getNetPay() ) );
}

文件内容:

00135
John Doe
10.50
0.20
00179
Mary Brown
12.50
1.20