ошибка при чтении данных, манипулировании ими и их выводе - PullRequest
0 голосов
/ 07 октября 2011

Вопрос завершен и не удалось удалить сообщение.

1 Ответ

2 голосов
/ 07 октября 2011

Полагаю, это потому, что у вас есть:

 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
...