Reputation: 31
in my head I'm initializing a variable named grade and using if else statement to change the variable. but I am getting a duplicate local variable error. I am returning double so I am initializing to 0.0. Am I understanding "scope" wrong here?
public static double finalGrade(double assignment, double midterm, double finalExam) {
double grade=0.0;
double midWorth = divide(midterm,20);
double finalWorth = divide(finalExam,45);
if(finalWorth < midWorth) {
double grade = divide((assignment + finalExam),80);
}
else {
double grade = divide((assignment + midterm + finalExam), 100);
}
return grade;
}
Upvotes: 0
Views: 255
Reputation: 6359
you need to specify the data type double
only once when you declare the variable. No need when you update the value.
There code be like,
public static double finalGrade(double assignment, double midterm, double finalExam) {
double grade=0.0; // declaring
double midWorth = divide(midterm,20);
double finalWorth = divide(finalExam,45);
if(finalWorth < midWorth) {
grade = divide((assignment + finalExam),80); // updating value
} else {
grade = divide((assignment + midterm + finalExam), 100); // updating value
}
return grade;
}
Upvotes: 0
Reputation: 44834
Think about the scope of variables
In
if(finalWorth < midWorth) {
double grade = divide((assignment + finalExam),80);
}
else {
double grade = divide((assignment + midterm + finalExam), 100);
}
The scope of the grade
variables in the if-else
are limited to the if-else
- not visible outside of the curly braces
so do
if(finalWorth < midWorth) {
grade = divide((assignment + finalExam),80);
}
else {
grade = divide((assignment + midterm + finalExam), 100);
}
Upvotes: 1