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


}
}

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

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?

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.

Ah...gotcha...thanks totally fixed now :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.