2013-10-20 42 views
0

在最後6條if語句中出現錯誤「局部變量操作可能未初始化」。我不知道我想要什麼。請幫忙! :(我已經嘗試了日食建議的修復,並試圖修復它在我自己並沒有什麼作品...局部變量動作可能未被初始化?

import java.util.Scanner; 
import static java.lang.System.out; 

public class test2 { 

enum dog {sleeping, eating, peeing, pooping, dead, robot} 

public static void main(String args[]) { 
    Scanner myScanner = new Scanner(System.in); 
    dog action; 
    int heartrate; 

    out.println("What is the heart rate of your dog? I will be able to tell you what the dog is doing from that information."); 
    heartrate = myScanner.nextInt(); 

    if (heartrate >= 60 || heartrate <= 120) { 
     action = dog.sleeping; 
    }else if (heartrate == 0) { 
     action = dog.dead; 
    }else if (heartrate > 500) { 
     action = dog.robot; 
    }else if (heartrate >= 150 || heartrate <= 200) { 
     action = dog.peeing; 
    }else if (heartrate >= 150 || heartrate <= 200) { 
     action = dog.pooping; 
    }else if (heartrate >= 150 || heartrate <= 200) { 
     action = dog.eating; 
    } 
    out.print("Your dog is currently "); 
    if (action == dog.sleeping) { 
     out.print("sleeping "); 
    } 
    if (action == dog.dead) { 
     out.print("dead "); 
    } 
    if (action == dog.robot) { 
     out.print("a robot."); 
    } 
    if (action == dog.peeing) { 
     out.print("peeing "); 
    } 
    if (action == dog.pooping) { 
     out.print("pooping "); 
    } 
    if (action == dog.eating) { 
     out.print("eating "); 
    } 
    System.out.println("."); 
} 
} 
+2

它希望*確保*行動已初始化,你沒有。 –

+1

**閱讀錯誤信息。**您需要確保您的代碼爲'action'指定了一個值。 –

+1

'if(heartrate> = 60 || heartrate <= 120)'意味着一隻沉睡的狗可能有負面的心率......也許你想'&&'在'x和y'之間而不是'||' – A4L

回答

2

你必須給變量的值,然後再使用它。例如action下不初始化所有條件,所以你不能安全地使用它。

一個簡單的辦法是給喜歡

dog action = dog.dead; 

取而代之的是一系列if(action ==報表的默認值,你可以使用一個switch塊。

順便說一句,你的三個條件是一樣的,你的IDE也應該警告你。