开发者

error when reading data, manipulating it, and outputting it

开发者 https://www.devze.com 2023-04-11 02:07 出处:网络
Having problems in my while loop. I\'m getting a Exception in thread "main" java.util.NoSuchElementException: No line found.

Having problems in my while loop. I'm getting a

Exception in thread "main" java.util.NoSuchElementException: No line found.
at java.util.Scanner.nextLine(Scanner.java:1516)
at Payroll.main(Payroll.java:70)`

Here's the code:

import javax.swing.JOptionPane;
import java.text.DecimalFormat;
import java.io.*;
import java.util.Scanner;

public class Payroll
{
public static void main(String[] args) throws IOException //throws exceptions
{
    //Declare variables
    String fileInput;               // To hold file input
    String fileOutput;              // To hold file output
    String date;                        // To hold the date
    String userInput;                   // To hold user input from JOptionPane
    String employeeID = "";         // To hold employee ID
    String employeeName = "";       // To hold employee name
    double hours = 0.0;             // To hold employee hours
    double wageRate = 0.0;          // To hold employee wage rate
    double taxRate = 0.0;           // To hold employee tax rate
    double taxWithheld;             // To hold employee taxes withheld
    double grossPay;                    // To hold employee gross pay
    double netPay;                      // To hold employee net pay
    double totalGross = 0.0;        // To hold total gross pay
    double totalTax = 0.0;          // To hold total tax withheld
    double totalNet = 0.0;          // To hold total net pay
    
    DecimalFormat money = new DecimalFormat("#,##0.00");// used to format money later on        
    
    date = JOptionPane.showInputDialog("Enter pay period ending date (mm/dd/yyyy): "); //hold user input into date
    
    //Open the input file
    File file = new File("EmployeeList.txt");
    
    if (!file.exists())// check to see if the file exists
        {
            JOptionPane.showMessageDialog(null, "The file EmployeeList.txt is not found.");
            System.exit(0);
        }  
        
    // Create Scanner object to enable reading data from input file
   Scanner inputFile = new Scanner(file);
    
    // Create FileWriter and PrintWriter objects to enable
  // writing (appending not overwriting) data to text file
  FileWriter fwriter = new FileWriter("PastPayrolls.txt", true);
  PrintWriter outputFile = new PrintWriter(fwriter);

    outputFile.println("PAY PERIOD ENDING DATE: " + date);
    
    
            
    while (inputFile.hasNext())
    {           
        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
        inputFile.nextLine();                                                       // Read blank line
        
        Paycheck paycheck = new Paycheck(employeeID, employeeName, wageRate, taxRate, hours);
        
        paycheck.calcWages();
        
        outputFile.println("Employee ID: " + paycheck.getEmployeeID());
开发者_开发技巧        outputFile.println("Name: " + paycheck.getEmployeeName());
        outputFile.println("Hours Worked: " + hours);
        outputFile.println("Wage Rate: $" + money.format(paycheck.getWageRate()));
        outputFile.println("Gross Pay: $" + money.format(paycheck.getGrossPay()));
        outputFile.println("Tax Rate: " + paycheck.getTaxRate());
        outputFile.println("Tax Withheld: $" + money.format(paycheck.getTaxWithheld()));
        outputFile.println("Net Pay: $" + money.format(paycheck.getNetPay()));
        
        
        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()));
        
        totalGross += paycheck.getGrossPay();
        totalTax += paycheck.getTaxWithheld();
        totalNet += paycheck.getNetPay();
        
        inputFile.nextLine();
        }

    }// end while loop
    
    JOptionPane.showMessageDialog(null, "Total Pay Period Gross Payroll: $" + money.format(totalGross) +
                                           "Total Pay Period Period Tax Withheld: $" +  money.format(totalTax)+
                                            "Total Pay Period Net Payroll: $" + money.format(totalNet));
    
    outputFile.println();
    outputFile.println("TOTAL PAY PERIOD GROSS PAYROLL: $" + money.format(totalGross));
    outputFile.println("TOTAL PAY PERIOD TAX WITHHELD: $" + money.format(totalTax));
    outputFile.println("TOTAL PAY PERIOD NET PAYROLL: $" + money.format(totalNet));
    
    inputFile.close();
    outputFile.close();
 }
}'

Here is the other code containing my paycheck class:

`public class Paycheck
{
//Declare variables
private final String EMPLOYEE_ID;       // Employee ID
private final String EMPLOYEE_NAME;     // Employee Name
private final double WAGE_RATE;         // Wage Rate
private final double TAX_RATE;          // Tax Rate
private final double HOURS_WORKED;      // Hours Worked
private double grossPay;                    // Gross Pay
private double taxWithheld;             // Tax Withheld
private double netPay;                      // Net Pay

// Constructor
Paycheck(String id, String name, double wage, double tax, double hours)
{
    EMPLOYEE_ID = id;
    EMPLOYEE_NAME = name;
    WAGE_RATE = wage;
    TAX_RATE = tax;
    HOURS_WORKED = hours;
}

public void calcWages()//calculates wages
{
    grossPay = HOURS_WORKED * WAGE_RATE;
    taxWithheld = grossPay * TAX_RATE;
    netPay = grossPay - taxWithheld;

}//end calcWages

public String getEmployeeID()//returns Employee's ID
{
    return EMPLOYEE_ID;
}//end getEmployeeID

public String getEmployeeName()//returns Employee's name
{
    return EMPLOYEE_NAME;
}//end getEmployeeName

public double getWageRate()//returns Employee's wage rate
{
    return WAGE_RATE;
}//end getWageRate

public double getTaxRate()//returns Employee's tax rate
{
    return TAX_RATE;
}//end getTaxRate

public double getHoursWorked()//returns Employee's hours worked
{
    return HOURS_WORKED;
}//end getHoursWorked

public double getGrossPay()//returns Employee's gross pay
{
    return grossPay;
}//end getGrossPay

public double getTaxWithheld()//returns Employee's tax withheld
{
    return taxWithheld;
}//end getTaxWithheld

public double getNetPay()//returns Employee's net pay
{
    return netPay;
}//end getNetPay
}`

Sorry for the lengthy code. I figured someone might need a good majority of the code to figure out what was going wrong. If there are better ways of doing things as far as using better methods, I am forced to stick to simplicity, so please try and work within the realms of this code. I am a beginner in Java btw.

Thanks!


I'm guessing it's because you have:

 while (inputFile.hasNext())

Use Scanner.hasNextLine.

Edit:

I tested your code with your sample input. I see what you mean now.

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

Using hasNextLine as your condition will only ensure that the next call to nextLine will be valid. But, your calling nextLine twice, and then calling nextDouble after that. You can either (1) ensure that the calls your making match up with the file exactly, or (2) check that there is a next token every time you call next. I think (1) is your problem.

I was able to fix your program with the following:

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

The file contents:

00135
John Doe
10.50
0.20
00179
Mary Brown
12.50
1.20
0

精彩评论

暂无评论...
验证码 换一张
取 消