Search code examples
javavariablesif-statementinitializing

java Local variable not initializing outside if-statement


Eclipse says that the variable age, agirl and aboy may not have been initialized. I initialized the variables before the first if statement and they got values in the if-statement. When I want to use them in the next if-statement eclipse says the local variables may not have been initialized. Here is my code:

import java.util.Scanner;

class Main{
public static void main(String args[]){
    Scanner input = new Scanner(System.in);
    String define;
    int aboy, agirl, age;
    System.out.println("Are you a boy or a girl?");
    define = input.next();

    if (define.equals("boy")){
        System.out.println("What is your age?");
        aboy = input.nextInt();
        age = aboy;
    }else if (define.equals ("girl")){
        System.out.println("What is your age?");
        agirl = input.nextInt();
        age = agirl;
    }else
        System.out.println("wrong answer");
    if (agirl >= 18 || aboy >= 16){
        System.out.println("You are a " + define + " and you are " + age  + " years old");
    }
}
}

Solution

  • Not only may you have an uninitialized variable, you're guaranteed to.

    Look at your control flow: You first ask for a value for define, and then you execute exactly one of the blocks. If define is "boy", you don't initialize agirl; if define is "girl", you don't initialize aboy, and if define doesn't match either, you don't initialize any of your variables at all.

    It looks like you are trying to cleverly combine the functions of a boolean and an int by having "magic" values in your ints. This is poor design because it's not clear how the magic works, but you can make your example run by initializing all of your int values to 0:

    int aboy = 0, agirl = 0, age = 0;