我正在尝试为创建工资单存根的类编写一个程序。我已经在网上查看了工作,我正在尝试创建自己的版本,但是我一直收到围绕我的main((是什么的错误,并且它无法正常运行。
我尝试重新组织代码、创建新文件和重命名内容,但仍然出现以下异常:
"Exception in thread "main" java.lang.Error: Unresolved compilation problem:
No enclosing instance of type Employee is accessible. Must qualify the allocation with an enclosing instance of type Employee (e.g. x.new A() where x is an instance of Employee).
at Employee.main(Employee.java:8)
我希望能够在我的代码中输入这些值:
import java.util.Scanner;
import java.util.*;
public class Employee{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
PayStub data = new PayStub();
System.out.println("Enter name: ");
data.setName(input.next());
System.out.println("Enter address: ");
data.setAddress(input.next());
System.out.println("Enter SSN: ");
data.setSSN((input.next()));
System.out.println("Number of hours: ");
data.setHoursWorked(Double.parseDouble(input.next()));
System.out.println("Enter hourly rate: ");
data.setHourlyPayRate(Double.parseDouble(input.next()));
input.close();
}
}
public class PayStub {
private String name;
private double hoursWorked;
private double hourlyRate;
private double fedTaxRate;
private double stateTaxRate;
private String address;
private String phone;
private String SSN;
public PayStub() {
}
public PayStub(String n, double w, double p) {
this.name = n;
this.hoursWorked = w;
this.hourlyRate = p;
}
public double grossPay(double hr, double hw) {
double grossPay = (hourlyRate * hoursWorked);
return grossPay;
}
public void setFedTax(double fedTaxRate) {
this.fedTaxRate = fedTaxRate;
}
public double getFedTax() {
return fedTaxRate;
}
public void setStateTax(double stateTaxRate) {
this.stateTaxRate = stateTaxRate;
}
public double getStateTax() {
return stateTaxRate;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getHoursWorked() {
return hoursWorked;
}
public void setHoursWorked(double hoursWorked) {
this.hoursWorked = hoursWorked;
}
public double getHourlyPayRate() {
return hourlyRate;
}
public void setHourlyPayRate(double hourlyRate) {
this.hourlyRate = hourlyRate;
}
public String getAddress(){
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone(){
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getSSN() {
return SSN;
}
public void setSSN(String SSN) {
this.SSN = SSN;
}
}
最简单的
解决方法是将公共类PayStub
移动到名为 PayStub.java
的文件。
您可以将PayStub
声明为静态类,使其成为Employee
的嵌套类,但没有理由这样做,因为PayStub
不是一种员工类型,而是员工拥有的东西。这是承包商可能拥有的东西,等等...所以你想把它拆分成它自己的文件,因为它是一个可重用的类。