0

Says grade isn't initializing

import java.util.*;


public class Test
{
static Scanner console = new Scanner(System.in);


public static void main(String[] args)
{
char grade;


switch (56 / 10)
{
case 0: case 1: case 2:
case 3: case 4: case 5: grade = 'F';
break;
case 6: grade = 'D';
case 7: grade = 'C';
case 8: grade = 'B';
case 9: case 10: grade = 'A';
break;
default: System.out.println("Invalid Test Score");
}
System.out.println(grade);


}
}

Edited by happygeek: fixed formatting

2
Contributors
4
Replies
5
Views
9 Years
Discussion Span
Last Post by jamminjelly
0

Actually, it complains that grade might not have been initialized. "grade" is only given a value in the switch statement, which is a conditional. This means it's possible that grade might not get any value assigned and your later code which uses the variable may fail. The compiler warns you of this and requires that you have a definite value assignment somewhere before the value gets used.

If you assign it a default value before the switch the compiler will be satisfied.

char grade = 'F';
0

but what if I wanted to change the number to something else in another statement? I would have to change grade to something else too...is there any other way to do that so it goes along with any number?

0

You can change it to whatever you like. You just need to be sure that it starts off with an initial value. In your current code, if the result of your expression were say 11, grade would never get a value. Then your println would try to print something that had no value. You can start with any default value you like as well, you just need to make sure it has one.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.