【问题标题】:The local variable action may not have been initialized?局部变量 action 可能没有初始化?
【发布时间】:2013-10-20 00:27:38
【问题描述】:

我在最后 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(".");
}
}

【问题讨论】:

  • 它要确保 action 被初始化,而你还没有。
  • 阅读错误信息。你需要确保你的代码为action赋值。
  • if (heartrate &gt;= 60 || heartrate &lt;= 120) 暗示睡狗的心率可能为负数......也许你想要&amp;&amp; 代替is between x and y 而不是||
  • 条件heartrate &gt;= 150 || heartrate &lt;= 200(以及其他几个类似的)可以替换为true——到目前为止,编译器实际上是错误的,这个程序确实会分配动作。

标签: java variables compiler-errors


【解决方案1】:

你必须在使用它之前给变量一个值。例如,action 并非在所有情况下都初始化,因此您无法安全地使用它。

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

dog action = dog.dead;

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

顺便说一句,你的三个条件是相同的,你的 IDE 也应该警告你。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-03
    相关资源
    最近更新 更多