0

I'm trying to write a program here, and in my if-else statement I have String messageToStudent initialize if taskCompleted == 'y' || taskCompleted == 'Y' , and in my else statement to initialize it for anything else. however, when I try to compile it says that messageToStudent may have not been initialized. Now, I thought I made it through the code that ONE of the messageToStudent strings would initialize, but I guess I was wrong. Here's what I have so far:

if(school == 1) {
    System.out.println(name + ", have you started your engineering project yet?");
    taskCompleted = scan.nextLine().charAt(0);
    if (taskCompleted == 'y' || taskCompleted == 'Y')
        messageToStudent = "Good for you! Keep me updated on your progress.";
    System.out.println(messageToStudent);
} else {
    messageToStudent = "That's not good at all. It's nearly November!";
}
System.out.println(messageToStudent);
Floegipoky
  • 3,087
  • 1
  • 31
  • 47
Azuma
  • 13
  • 1
  • 5
  • The compiler isn't smart enough. Give it an initial value of `""` or `null` when you declare the variable. – Jeroen Vannevel Oct 28 '14 at 21:26
  • 1
    If school is `1` and taskCompleted is `N`, where is `messageToStudent` initialized? – azurefrog Oct 28 '14 at 21:26
  • you should read up on [NullPointerException](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – benscabbia Oct 28 '14 at 21:27
  • From your code, it looks like you're intending to put the `System.out.println(messageToStudent)` inside the `if`-`else` statements, instead of right after them. That, or you're yet to add an `else` statement for when `school == 1`, but taskCompleted is not `y` or `Y` (and initialize `messageToStudent` there as well). In any of those two cases, once your code has been fixed, there wouldn't be a need to initialize `messageToStudent` to `null` or `""` at the beginning, as it will already be initialized when you want to print it. – Lone nebula Oct 28 '14 at 22:19

1 Answers1

2

What if school was 1 but taskCompleted wasn't 'y' or 'Y'? That is the path where messageToStudent was not initialized.

Provide a value, even if it's an empty string or null at the top, so it is always initialized.

rgettman
  • 176,041
  • 30
  • 275
  • 357