Question

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");
    }
}
}
Was it helpful?

Solution 2

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;

OTHER TIPS

This line

int aboy, agirl, age;

contains declarations, not initializations. Java will not initialize a local variable for you, and there is an execution path (the else) where nothing is ever assigned to those variables, then you attempt to reference their nonexistent values.

You must set values to them before you use them, in all execution paths. Initialize them to something when you declare them.

Initializing is assigning the variable a value. Declaring is creating the variable. They are not the same.

The reason you need to initialize the variables is because it is possible they will not be initialized. All the if statements could be false, thus you need to give them a default value.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top