【发布时间】: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 >= 60 || heartrate <= 120)暗示睡狗的心率可能为负数......也许你想要&&代替is between x and y而不是|| -
条件
heartrate >= 150 || heartrate <= 200(以及其他几个类似的)可以替换为true——到目前为止,编译器实际上是错误的,这个程序确实会分配动作。
标签: java variables compiler-errors