2016-04-04 50 views
-1

我得到這個「局部變量名詞可能沒有被初始化」的錯誤,我不知道爲什麼?如果我初始化的變量設置爲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); 


    } 
+1

如果名詞是'null''noun.equals(「dork」)'崩潰。 – Berger

+0

你缺少'noun = input.nextLine();' – starf

回答

1

一旦崩潰,這是問題所在:

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

將這個前行,如果

noun = input.nextLine(); 
3

您收到的錯誤消息是由於在可能尚未初始化的位置使用變量noun而導致的d已經在代碼中。您可以在之前嘗試將用戶輸入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); 
}