开发者

Java, "Variable name" cannot be resolved to a variable

I use Eclipse using Java, I get this error:

"Variable name" cannot be resolved to a variable.

With this Java program:

public class SalCal {
    private int hoursWorked;
    public SalCal(String name, int hours, double hoursRate) {
        nameEmployee = name;
        hoursWorked = hours;
        ratePrHour = hoursRate;
    }
    public v开发者_如何学编程oid 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;
    }
}

What causes this error message?


If you look at the scope of the variable 'hoursWorked' you will see that it is a member of the class (declared as private int)

The two variables you are having trouble with are passed as parameters to the constructor.

The error message is because 'hours' is out of scope in the setter.


public void setHoursWorked(){
    hoursWorked = hours;
}

You haven't defined hours inside that method. hours is not passed in as a parameter, it's not declared as a variable, and it's not being used as a class member, so you get that error.


I've noticed bizarre behavior with Eclipse version 4.2.1 delivering me this error:

String cannot be resolved to a variable

With this Java code:

if (true)
    String my_variable = "somevalue";
    System.out.println("foobar");

You would think this code is very straight forward, the conditional is true, we set my_variable to somevalue. And it should print foobar. Right?

Wrong, you get the above mentioned compile time error. Eclipse is trying to prevent you from making a mistake by assuming that both statements are within the if statement.

If you put braces around the conditional block like this:

if (true){
    String my_variable = "somevalue"; }
    System.out.println("foobar");

Then it compiles and runs fine. Apparently poorly bracketed conditionals are fair game for generating compile time errors now.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜