Java,“变量名”无法解析为变量

2022-09-02 09:55:19

我使用Java使用Eclipse,我得到这个错误:

"Variable name" cannot be resolved to a variable.

有了这个Java程序:

public class SalCal {
    private int hoursWorked;
    public SalCal(String name, int hours, double hoursRate) {
        nameEmployee = name;
        hoursWorked = hours;
        ratePrHour = hoursRate;
    }
    public void setHoursWorked() {
        hoursWorked = hours;     //ERROR HERE, hours cannot be resolved to a type
    }
    public double calculateSalary() {
        if (hoursWorked <= 40) {
            totalSalary = ratePrHour * (double) hoursWorked;
        }
        if (hoursWorked > 40) {
            salaryAfter40 = hoursWorked - 40;
            totalSalary = (ratePrHour * 40)
                + (ratePrHour * 1.5 * salaryAfter40);
        }
        return totalSalary;
    }
}

导致此错误消息的原因是什么?


答案 1

如果您查看变量“hoursWorked”的作用域,您将看到它是该类的成员(声明为私有int)

您遇到问题的两个变量将作为参数传递给构造函数。

错误消息是因为“小时”超出了 setter 中的范围。


答案 2
public void setHoursWorked(){
    hoursWorked = hours;
}

您尚未在该方法中定义。hours 不会作为参数传入,它不会声明为变量,也不会用作类成员,因此您会收到该错误。hours