gpt4 book ai didi

java 枚举 - 在其他 java 文件中使用时不编译

转载 作者:行者123 更新时间:2023-12-01 10:34:28 26 4
gpt4 key购买 nike

我正在尝试使用 Java 枚举,但代码无法编译。我在整个代码中收到以下错误。

Class, interface, or enum expected

错误

vm@vm:~/Documents/Oops/DesignPatterns/CommandPattern$ javac Kitchen.java

Kitchen.java:1: '.' expected
import HomeApplianceAction;
^
Kitchen.java:1: ';' expected
import HomeApplianceAction;
^
Kitchen.java:3: class, interface, or enum expected
class Kitchen{
^
Kitchen.java:5: class, interface, or enum expected
private Door_Enum kitchen_door;
^
Kitchen.java:6: class, interface, or enum expected
private Fan_Enum exhaust_fan;
^
Kitchen.java:8: class, interface, or enum expected
Kitchen(){
^
Kitchen.java:10: class, interface, or enum expected
this.kitchen_door = Door_Enum.DOOR_SHUT;
^
Kitchen.java:11: class, interface, or enum expected
this.exhaust_fan = Fan_Enum.FAN_SWITCHED_OFF;
^
Kitchen.java:12: class, interface, or enum expected
}
^
Kitchen.java:14: class, interface, or enum expected
public void setKitchenLights(Light_Enum kitchen_light){

如何修复此错误消息?

这是代码片段:

public interface HomeApplianceAction{
}

enum Light_Enum implements HomeApplianceAction{
LIGHTS_ON,
LIGHTS_OFF,
LIGHTS_DIM;
}

enum Door_Enum implements HomeApplianceAction{
DOOR_OPEN,
DOOR_SHUT;
}

enum TV_Enum implements HomeApplianceAction{
TV_POWERED_ON,
TV_POWERED_OFF,
TV_STANDBY;
}

enum Computer_Enum implements HomeApplianceAction{
COMP_POWERED_ON,
COMP_POWERED_OFF,
COMP_STANDBY,
COMP_SLEEP,
COMP_HIBERNATE;
}

enum Fan_ENUM implements HomeApplianceAction{
FAN_SWITCHED_OFF,
FAN_LOW,
FAN_MEDIUM,
FAN_HIGH;
}

上面的代码放在HomeApplianceAction.java文件中并且编译成功。现在我想在 Kitchen.java 文件中使用这些枚举,如下所示:

import HomeApplianceAction;

class Kitchen{
private Light_Enum kitchen_light;
private Door_Enum kitchen_door;
private Fan_Enum exhaust_fan;

Kitchen(){
this.kitchen_light = Light_Enum.LIGHTS_OFF;
this.kitchen_door = Door_Enum.DOOR_SHUT;
this.exhaust_fan = Fan_Enum.FAN_SWITCHED_OFF;
}

public void setKitchenLights(Light_Enum kitchen_light){
this.kitchen_light = kitchen_light;
}

public void setKitchenDoor(Door_Enum kitchen_door){
this.kitchen_door = kitchen_door;
}

public void setKitchenExhaustFan(Fan_Enum exhaust_fan){
this.exhaust_fan = exhaust_fan;
}

public void execute(HomeApplianceAction action){
if(action instanceof Light_Enum){
setKitchenLights(action);
}
else if(action instanceof Door_Enum){
setKitchenDoor(action);
}
else if(action instanceof Fan_Enum){
setKitchenExhaustFan(action);
}
else{
System.out.println("Invalid action performed on Kitchen Appliance");
}
}
}

最佳答案

您有一个包含多个枚举和一个公共(public)接口(interface)的文件。文件“.java”称为编译单元。每个编译单元只能有一个公共(public)类、接口(interface)或枚举。

您可以为每个枚举创建单独的编译单元,也可以在接口(interface)中实现枚举并按如下方式访问它:

HomeApplianceAction.Computer_Enum.COMP_HIBERNATE

否则,您的枚举仅在界面内可见。

关于java 枚举 - 在其他 java 文件中使用时不编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34862737/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com