读取数据、操作数据和输出数据时出错

发布于 2024-12-08 13:53:09 字数 7955 浏览 0 评论 0原文

我的 while 循环出现问题。我收到了

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

这是代码:

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

这是包含我的薪水类的其他代码:

`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
}`

抱歉代码太长。我认为有人可能需要大部分代码才能找出问题所在。如果有更好的方法来使用更好的方法,我将被迫坚持简单性,所以请尝试在这段代码的范围内工作。顺便说一句,我是 Java 初学者。

谢谢!

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: 
quot; + money.format(paycheck.getWageRate()));
        outputFile.println("Gross Pay: 
quot; + money.format(paycheck.getGrossPay()));
        outputFile.println("Tax Rate: " + paycheck.getTaxRate());
        outputFile.println("Tax Withheld: 
quot; + money.format(paycheck.getTaxWithheld()));
        outputFile.println("Net Pay: 
quot; + money.format(paycheck.getNetPay()));
        
        
        JOptionPane.showMessageDialog(null, "Employee ID: " + paycheck.getEmployeeID() +
                                               "\nName: " + paycheck.getEmployeeName() +
                                                "\nHours Worked: " + hours +
                                                "\nWage Rate: 
quot; + money.format(paycheck.getWageRate()) +
                                                "\nGross Pay: 
quot; + money.format(paycheck.getGrossPay()) +
                                                "\nTax Rate: " + paycheck.getTaxRate() +
                                                "\nTax Withheld: 
quot; + money.format(paycheck.getTaxWithheld()) +
                                                "\nNet Pay: 
quot; + 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: 
quot; + money.format(totalGross) +
                                           "Total Pay Period Period Tax Withheld: 
quot; +  money.format(totalTax)+
                                            "Total Pay Period Net Payroll: 
quot; + money.format(totalNet));
    
    outputFile.println();
    outputFile.println("TOTAL PAY PERIOD GROSS PAYROLL: 
quot; + money.format(totalGross));
    outputFile.println("TOTAL PAY PERIOD TAX WITHHELD: 
quot; + money.format(totalTax));
    outputFile.println("TOTAL PAY PERIOD NET PAYROLL: 
quot; + 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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

缪败 2024-12-15 13:53:09

我猜这是因为您有:

 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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文