局部变量名词可能尚未初始化

时间:2016-04-04 15:04:26

标签: java

我得到了这个"局部变量名词可能尚未初始化"错误,我不知道为什么?如果我将变量初始化为null noun = null,则程序一执行就会崩溃System.out.println("Enter noun: ");

    int age;
    System.out.println("Enter your age: ");
    age = input.nextInt();
    String name, adjective, adverb, verb, noun;

    if(age > 13) {

        System.out.println("Enter name: ");
        name = input.nextLine();
        input.nextLine();
        System.out.println("Enter adjective: ");
        adjective = input.nextLine();
        System.out.println("Enter noun: ");
        if(noun.equals("dork")){
            System.out.println("That language is not allowed. Exiting");
            System.exit(0);
        } else {
        noun = input.nextLine();
        System.out.println("Enter adverb: ");
        adverb = input.nextLine();
        System.out.println("Enter verb: ");
        verb = input.nextLine();
        System.out.printf("%s is a %s %s. They are always %s %s", name, adjective, noun, adverb, verb);
        }
    } else {
        System.out.printf("Your age is %s and You're still young to access this information", age);


    }

2 个答案:

答案 0 :(得分:3)

您获得的错误消息是由于在代码中可能尚未初始化的位置使用变量noun而导致的。在检查其值之前,您可以尝试将noun设置为用户输入。这应该摆脱错误,同时让你的代码处于更合理和可读的位置:

System.out.println("Enter noun: ");
noun = input.nextLine();
if (noun.equals("dork")) {
    System.out.println("That language is not allowed. Exiting");
    System.exit(0);
}

答案 1 :(得分:1)

问题在于:

if(noun.equals("dork")){

将此行放在if

之前
noun = input.nextLine();