Skip to content
Advertisement

Java name generator variable is already defined in method main(String[]) [closed]

I am new, having a problem with my code. I wonder how will I be able to print a variable after the if statements. When I don’t put the variable before the if statement it says that it’s not initialized. here is the code:

import java.util.Scanner;

public class NameGenerator { public static void main(String[] args) {

Scanner getInput = new Scanner(System.in);

System.out.println("What's the first letter of your first name? ");
String name = getInput.nextLine();

String xmas2;

if (name.equalsIgnoreCase ("a"))  {
    String xmas2 = "Christmas";
    
} else if (name.equalsIgnoreCase ("b")) {
    String xmas2 = "Merry";
    
} else if (name.equalsIgnoreCase ("c")) {
    String xmas2 = "Santa";
    
} else if(name.equalsIgnoreCase ("d")) {
    String xmas2 = "Chocolate";
    
} else if(name.equalsIgnoreCase ("e")) {
    String xmas2 = "Tinsel";
    
} else if(name.equalsIgnoreCase ("f")) {
    String xmas2 = "Yule";
}

System.out.println("Hey " + xmas2);

}

}

Advertisement

Answer

First of all, you assign variable only 1 time ” String xmas2 = null;”

import java.util.Scanner;

public class Practice {
    public static void main(String[] args) {

        Scanner getInput = new Scanner(System.in);

        System.out.println("What's the first letter of your first name? ");
        String name = getInput.nextLine();

        String xmas2 = null;

        if (name.equalsIgnoreCase("a")) {
            xmas2 = "Christmas";

        } else if (name.equalsIgnoreCase("b")) {
            xmas2 = "Merry";

        } else if (name.equalsIgnoreCase("c")) {
            xmas2 = "Santa";

        } else if (name.equalsIgnoreCase("d")) {
            xmas2 = "Chocolate";

        } else if (name.equalsIgnoreCase("e")) {
            xmas2 = "Tinsel";

        } else if (name.equalsIgnoreCase("f")) {
            xmas2 = "Yule";
        }

        System.out.println("Hey " + xmas2);

    }
}

Output

What's the first letter of your first name? 
a

Hey Christmas
Advertisement