Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

What causes this error message?

like image 598
user820913 Avatar asked Sep 28 '11 19:09

user820913


People also ask

Can not be resolved to a variable in Java?

Fix the cannot be resolved to a variable Error in Java If you try, the cannot be resolved to a variable error will come out. It means it cannot detect the initialization of variables within its scope. Similarly, if you make a private variable, you cannot call it inside a constructor. Its scope is out of bounds.

Which of the Cannot be used for a variable name in Java?

A variable name should start with an alphabetic character (like a, b, c, etc). You can't use any of the keywords or reserved words as variable names in Java ( for , if , class , static , int , double , etc).

How do you initialize a variable in Java?

The syntax for an initializer is the type, followed by the variable name, followed by an equal sign, followed by an expression. That expression can be anything, provided it has the same type as the variable. In this case, the expression is 10, which is an int literal.


2 Answers

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.

like image 99
Hugh Jones Avatar answered Oct 15 '22 23:10

Hugh Jones


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.

like image 35
Marc B Avatar answered Oct 15 '22 22:10

Marc B