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?
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.
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).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With