1
import java.util.Scanner;

class Practice {

public static void main(String args[]) {        


    System.out.println("Please enter your test score: ");
    Scanner enteredScore = new Scanner(System.in);
    int testScore = (enteredScore.nextInt());


    char grade = 'A';        

    if (testScore >= 90) {
        grade = 'A';            
    }                
    else if (testScore >= 80) {
        grade = 'B';
    }                
    else if (testScore >= 70) {
        grade = 'C';
    }        
    else if (testScore >= 60) {
        grade = 'D';
    }        
    else if (testScore >= 0) {
        grade = 'U';
    }


    System.out.println("Your grade is a " + grade + ".");

}
}

Could someone explain to me why I have to initialise "char grade = 'A';" before my "if" statement, rather than simply declaring it, "char grade;"?

Thanks.

5 Answers 5

8

There's a possibility that none of the if..else if is true. So you should either initialize the grade or add an else condition at the bottom.

6

Your if/else construct doesn't cover all code branches. If testScore is less than zero, grade will be unitialized and your System.out.println call would fail.

3

you can declare it as "char grade," but you need an else statement.

Let's say you had char grade; instead of char grade = 'A';

Let's also say, hypothetically, testscore was a negative number.

The compiler would go past all of your if conditions without grade being initialized to a letter.The java compiler wants to be sure you have all your bases covered before you can proceed. Depending upon your program requirements, I would change the last statement to an else statement rather than an else if.

1

Java does not know that your testScore is never negative (and in more complex cases it cannot deduce such information). Thus it may be that none of the if clauses holds and the variable grade would be unitialized.

1

I would leave the variable uninitialized, and let the compiler tell me that there is a code branch that does not assign a value to the variable. This tells you that not all possible inputs are being handled. With you're current code a negative value is an A, which is not right.

I would add an extra else statement that prints an error message and quits. Then the compiler will accept uninitialized variable and all input paths are covered (expect for the non number input, which will produce an exception on the call to nextInt().

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.