局部变量动作可能尚未初始化?

时间:2013-10-20 00:27:38

标签: java variables compiler-errors

我在最后6个if语句中收到错误“本地变量操作可能尚未初始化”。我不知道它对我有什么要求。请帮忙! :(我已经尝试过eclipse建议修复并尝试自行解决它并且没有任何作用......

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(".");
}
}

1 个答案:

答案 0 :(得分:2)

在使用变量之前,必须为变量赋值。例如,action未在所有条件下初始化,因此您无法安全地使用它。

一个简单的解决方案是提供一个默认值,如

dog action = dog.dead;

您可以使用一个if(action ==块来代替一系列switch语句。

BTW您的三个条件是相同的,您的IDE也应该警告您。