Ben
Ben

Reputation: 13

Why do I need to initialise this?

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.

Upvotes: 1

Views: 204

Answers (5)

Michael Krussel
Michael Krussel

Reputation: 2656

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().

Upvotes: 1

Alan
Alan

Reputation: 281

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.

Upvotes: 3

Howard
Howard

Reputation: 39197

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.

Upvotes: 1

joschi
joschi

Reputation: 13101

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.

Upvotes: 6

asgs
asgs

Reputation: 3984

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.

Upvotes: 8

Related Questions