2014-10-26 115 views
0

我有一個greetingLoop被main()中的開關case調用,如果它返回null,用戶輸入被要求一次,但沒有做任何事情。我試圖避免greetingLoop()返回null,但只要將返回變量userInput放入if語句中,它就不會被eclipse識別,「此方法必須返回一個int類型」。阻止返回null的方法java

任何提示將不勝感激,謝謝。

public static int greetingLoop(){ 

    int userInput=0; 
    try{ 
      System.out.println("Please enter the desired operation:"); 
      System.out.println("1.Insert, 2.Delete, 3.Edit, 4.Show, 5.List, 6.Volume, 7.Exit\n"); 
       userInput=Integer.parseInt(JOptionPane.showInputDialog("Please enter the desired 
       operation:")); 
    } 
    catch (NumberFormatException ne){ 
     System.out.println("your input " + userInput + " is not valid. Please try again...\n"); 
    } 

    if(userInput >= 1 && <= 7){ 
     return userInput; 
     } 
    } 

回答

0

這是因爲你沒有在if條件謂詞是false

在任何速率if聲明

}之後添加return userInput;的情況下返回任何東西,你永遠不能迴歸null,因爲你的返回類型是原始的int,並且總會返回一個int值。

所以,在這種情況下,如果您添加return userInput;在你的方法的最後一行,它將返回初始值0