Variable might not have been initialized?
Hey there, looking for help, we are building a grade calculator where we are trying to used a method within a method (code will explain) however i keep getting this variable not initialized and i dont know why heres my code:
Code Java:
import java.util.Scanner;
public class StudentGradesWeek7
{
public static void main(String[] args)
{
String input = "";
while (!input.equals("q"))
{
Scanner in = new Scanner(System.in);
System.out.println("Enter student grade percentage or 'q' to exit:");
input = in.nextLine();
if (!input.equals("q"))
{
int inputMark = Integer.parseInt(input);
char g = getGrade(inputMark);
System.out.println("The students grade is:" + g);
}
}
}
private static char getGrade(int mark)
{
char grade;
if (mark >= 70)
{
grade = 'A';
}
else if (mark >= 65)
{
grade = 'B';
}
else if (mark >= 55)
{
grade = 'C';
}
else if (mark >= 45)
{
grade = 'D';
}
else if (mark >= 44)
{
grade = 'F';
}
return grade;
}
}
The program is supposed to ask what percentage grade the student received then issue them the grade, it will then ask again or ask them to enter q for the program to exit, any help is much appreciated!!
Thank you, Nathan
EDIT: its the last line: return grade; which is giving me the problem
Re: Variable might not have been initialized?
Here's the problem: What if mark is less than 44? What should be returned then?
In other words, not every path of execution results in grade being initialized.
Re: Variable might not have been initialized?
Give the char some default value like 'c'.
Re: Variable might not have been initialized?
Quote:
Originally Posted by
javapenguin
Give the char some default value like 'c'.
Again, that's pretty bad advice. How does that answer the underlying problem? What if the grade is less than 44? Should "some default value like 'c'" be returned? No. The OP should fix the logic problem, not cover it up with hacky solutions.
Edit- In fact, part of the error is a typo on the OP's fault. If he thinks about why I asked my original question, he'll figure it out. If he applies your "solution", he'll fail his assignment.
Re: Variable might not have been initialized?
I feel like a douche, ive got a More than or equal to 44, not less than or equal too, okay i changed that and it works, thank you very much, dammit i knew it would be something simple lol, thanks again.
Re: Variable might not have been initialized?
Quote:
Originally Posted by
KevinWorkman
Again, that's pretty bad advice. How does that answer the underlying problem? What if the grade is less than 44? Should "some default value like 'c'" be returned? No. The OP should fix the logic problem, not cover it up with hacky solutions.
Edit- In fact, part of the error is a typo on the OP's fault. If he thinks about why I asked my original question, he'll figure it out. If he applies your "solution", he'll fail his assignment.
#-o
Good point, what was I thinking?