Java 使用 enum 和 switch 语句

发布于 2024-12-15 08:05:49 字数 962 浏览 0 评论 0原文

我查看了与此问题类似的各种问答,但尚未找到解决方案。

我拥有的是一个枚举,它代表观看电视指南的不同方式...

在 NDroid Application 类中

static enum guideView {
    GUIDE_VIEW_SEVEN_DAY,
    GUIDE_VIEW_NOW_SHOWING,
    GUIDE_VIEW_ALL_TIMESLOTS
}

...当用户更改视图时,事件处理程序会收到一个 int 从 0-2 ,我想做这样的事情...

在 Android Activity onClick(DialogInterfacedialog, int which) 事件处理程序中,

// 'which' is an int from 0-2
switch (which) {
    case NDroid.guideView.GUIDE_VIEW_SEVEN_DAY:
    ...
    break;
}

我用于 C# 枚举和 select/case 语句,这将允许类似上面我知道 Java 的做法不同,但我就是不明白我需要做什么。

我是否必须求助于 if 语句?可能只有 3 个选择,所以我可以做到这一点,但我想知道如何使用 Java 中的 switch-case 来完成它。

编辑 抱歉,我没有完全扩展这个问题,因为我将其视为一个通用的 Java 问题。我已添加到问题中以进一步解释。

没有任何特定于 Android 的内容,这就是为什么我没有将其标记为 Android,但枚举是在 Application 类中定义的,并且我不希望切换的代码位于 活动。枚举是静态的,因为我需要从多个活动访问它。

I've looked at various Q&As on SO similar to this question but haven't found a solution.

What I have is an enum which represents different ways to view a TV Guide...

In the NDroid Application class

static enum guideView {
    GUIDE_VIEW_SEVEN_DAY,
    GUIDE_VIEW_NOW_SHOWING,
    GUIDE_VIEW_ALL_TIMESLOTS
}

...when the user changes the view an event handler receives an int from 0-2 and I'd like to do something like this...

In an Android Activity onClick(DialogInterface dialog, int which) event handler

// 'which' is an int from 0-2
switch (which) {
    case NDroid.guideView.GUIDE_VIEW_SEVEN_DAY:
    ...
    break;
}

I'm used to C# enums and select/case statements which would allow something like the above and I know Java does things differently but I just can't make sense of what I need to do.

Am I going to have to resort to if statements? There will likely only ever be 3 choices so I could do it but I wondered how it could be done with switch-case in Java.

EDIT Sorry I didn't completely expand on the issue as I was looking at it as being a generic Java issue. I've added to the question to explain a bit further.

There isn't anything that's Android specific which is why I didn't tag it as Android but the enum is defined in the Application class and the code where I wan't the switch is in an Activity. The enum is static as I need to access it from multiple Activities.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

您缺少的部分是将整数转换为类型安全枚举。 Java 不会自动执行此操作。有几种方法可以解决此问题:

  1. 使用静态最终 int 列表而不是类型安全枚举,并打开收到的 int 值(这是 Java 5 之前的方法)
  2. 打开指定的 id 值(如描述heneryville) 或枚举值的序数值;即guideView.GUIDE_VIEW_SEVEN_DAY.ordinal()
  3. 确定int值表示的枚举值,然后开启枚举值。

    枚举 GuideView {
        七日,
        NOW_SHOWING,
        ALL_TIMESLOTS
    }
    
    // 假设你的 int 值是 
    // 枚举中项目的序数值
    公共无效onClick(DialogInterface对话框,int其中){
        // 进行自己的边界检查
        GuideView whichView = GuideView.values()[which];
        开关(哪个视图){
            案例 SEVEN_DAY:
                ...
                休息;
            案例NOW_SHOWING:
                ...
                休息;
        }
    }
    

    您可能会发现编写自定义 valueOf 实现更有帮助/更不容易出错,该实现将整数值作为参数来解析适当的枚举值,并让您集中边界检查。

The part you're missing is converting from the integer to the type-safe enum. Java will not do it automatically. There's a couple of ways you can go about this:

  1. Use a list of static final ints rather than a type-safe enum and switch on the int value you receive (this is the pre-Java 5 approach)
  2. Switch on either a specified id value (as described by heneryville) or the ordinal value of the enum values; i.e. guideView.GUIDE_VIEW_SEVEN_DAY.ordinal()
  3. Determine the enum value represented by the int value and then switch on the enum value.

    enum GuideView {
        SEVEN_DAY,
        NOW_SHOWING,
        ALL_TIMESLOTS
    }
    
    // Working on the assumption that your int value is 
    // the ordinal value of the items in your enum
    public void onClick(DialogInterface dialog, int which) {
        // do your own bounds checking
        GuideView whichView = GuideView.values()[which];
        switch (whichView) {
            case SEVEN_DAY:
                ...
                break;
            case NOW_SHOWING:
                ...
                break;
        }
    }
    

    You may find it more helpful / less error prone to write a custom valueOf implementation that takes your integer values as an argument to resolve the appropriate enum value and lets you centralize your bounds checking.

你爱我像她 2024-12-22 08:05:49

如果 whichView 是 GuideView 枚举的对象,则以下效果很好。请注意,case 之后的常量没有限定符。

switch (whichView) {
    case SEVEN_DAY:
        ...
        break;
    case NOW_SHOWING:
        ...
        break;
}

If whichView is an object of the GuideView Enum, following works well. Please note that there is no qualifier for the constant after case.

switch (whichView) {
    case SEVEN_DAY:
        ...
        break;
    case NOW_SHOWING:
        ...
        break;
}
起风了 2024-12-22 08:05:49

枚举不应像 NDroid.guideView.GUIDE_VIEW_SEVEN_DAY 那样在 case 标签内进行限定,而是应删除限定并使用 GUIDE_VIEW_SEVEN_DAY

The enums should not be qualified within the case label like what you have NDroid.guideView.GUIDE_VIEW_SEVEN_DAY, instead you should remove the qualification and use GUIDE_VIEW_SEVEN_DAY

风吹雪碎 2024-12-22 08:05:49

我喜欢 Java 枚举的一些用法:

  1. .name() 允许您获取字符串中的枚举名称。
  2. .ordinal() 允许您获取从 0 开始的整数值。
  3. 您可以为每个枚举附加其他值参数。
  4. 当然,还有开关启用。

具有值参数的枚举:

    enum StateEnum {
        UNDEFINED_POLL  ( 1 * 1000L,       4 * 1000L),
        SUPPORT_POLL    ( 1 * 1000L,       5 * 1000L),
        FAST_POLL       ( 2 * 1000L,  4 * 60 * 1000L),
        NO_POLL         ( 1 * 1000L,       6 * 1000L); 
        ...
    }

开关示例:

private void queuePoll(StateEnum se) {
    // debug print se.name() if needed
    switch (se) {
        case UNDEFINED_POLL:
            ...
            break;
        case SUPPORT_POLL:
            ...
            break;

I like a few usages of Java enum:

  1. .name() allows you to fetch the enum name in String.
  2. .ordinal() allow you to get the integer value, 0-based.
  3. You can attach other value parameters with each enum.
  4. and, of course, switch enabled.

enum with value parameters:

    enum StateEnum {
        UNDEFINED_POLL  ( 1 * 1000L,       4 * 1000L),
        SUPPORT_POLL    ( 1 * 1000L,       5 * 1000L),
        FAST_POLL       ( 2 * 1000L,  4 * 60 * 1000L),
        NO_POLL         ( 1 * 1000L,       6 * 1000L); 
        ...
    }

switch example:

private void queuePoll(StateEnum se) {
    // debug print se.name() if needed
    switch (se) {
        case UNDEFINED_POLL:
            ...
            break;
        case SUPPORT_POLL:
            ...
            break;
北座城市 2024-12-22 08:05:49

简短的关联函数示例:

public String getIcon(TipoNotificacao tipo)
{
    switch (tipo){
        case Comentou : return "fa fa-comments";
        case ConviteEnviou : return "icon-envelope";
        case ConviteAceitou : return "fa fa-bolt";
        default: return "";
    }
}

就像@Dhanushka所说,省略“switch”内的限定符是关键。

Short associative function example:

public String getIcon(TipoNotificacao tipo)
{
    switch (tipo){
        case Comentou : return "fa fa-comments";
        case ConviteEnviou : return "icon-envelope";
        case ConviteAceitou : return "fa fa-bolt";
        default: return "";
    }
}

Like @Dhanushka said, omit the qualifier inside "switch" is the key.

小傻瓜 2024-12-22 08:05:49

这应该按照您描述的方式工作。你遇到什么错误?如果你可以粘贴你的代码会有帮助。

http://download.oracle.com/javase/tutorial/java/javaOO /enum.html

编辑:您确定要定义静态枚举吗?这对我来说听起来不对。枚举与任何其他对象非常相似。如果您的代码编译并运行但给出了不正确的结果,这可能就是原因。

This should work in the way that you describe. What error are you getting? If you could pastebin your code that would help.

http://download.oracle.com/javase/tutorial/java/javaOO/enum.html

EDIT: Are you sure you want to define a static enum? That doesn't sound right to me. An enum is much like any other object. If your code compiles and runs but gives incorrect results, this would probably be why.

故笙诉离歌 2024-12-22 08:05:49
enumerations accessing is very simple in switch case

private TYPE currentView;

//declaration of enum 
public enum TYPE {
        FIRST, SECOND, THIRD
    };

//handling in switch case
switch (getCurrentView())
        {
        case FIRST:
            break;
        case SECOND:
            break;
        case THIRD:
            break;
        }

//getter and setter of the enum
public void setCurrentView(TYPE currentView) {
        this.currentView = currentView;
    }

    public TYPE getCurrentView() {
        return currentView;
    }

//usage of setting the enum 
setCurrentView(TYPE.FIRST);

avoid the accessing of TYPE.FIRST.ordinal() it is not recommended always
enumerations accessing is very simple in switch case

private TYPE currentView;

//declaration of enum 
public enum TYPE {
        FIRST, SECOND, THIRD
    };

//handling in switch case
switch (getCurrentView())
        {
        case FIRST:
            break;
        case SECOND:
            break;
        case THIRD:
            break;
        }

//getter and setter of the enum
public void setCurrentView(TYPE currentView) {
        this.currentView = currentView;
    }

    public TYPE getCurrentView() {
        return currentView;
    }

//usage of setting the enum 
setCurrentView(TYPE.FIRST);

avoid the accessing of TYPE.FIRST.ordinal() it is not recommended always
疯狂的代价 2024-12-22 08:05:49

我这样做就像

public enum State
{
    // Retrieving, // the MediaRetriever is retrieving music //
    Stopped, // media player is stopped and not prepared to play
    Preparing, // media player is preparing...
    Playing, // playback active (media player ready!). (but the media player
                // may actually be
                // paused in this state if we don't have audio focus. But we
                // stay in this state
                // so that we know we have to resume playback once we get
                // focus back)
    Paused; // playback paused (media player ready!)

    //public final static State[] vals = State.values();//copy the values(), calling values() clones the array

};

public State getState()
{
        return mState;   
}

在 Switch 语句中使用一样

switch (mService.getState())
{
case Stopped:
case Paused:

    playPause.setBackgroundResource(R.drawable.selplay);
    break;

case Preparing:
case Playing:

    playPause.setBackgroundResource(R.drawable.selpause);
    break;    
}

I am doing it like

public enum State
{
    // Retrieving, // the MediaRetriever is retrieving music //
    Stopped, // media player is stopped and not prepared to play
    Preparing, // media player is preparing...
    Playing, // playback active (media player ready!). (but the media player
                // may actually be
                // paused in this state if we don't have audio focus. But we
                // stay in this state
                // so that we know we have to resume playback once we get
                // focus back)
    Paused; // playback paused (media player ready!)

    //public final static State[] vals = State.values();//copy the values(), calling values() clones the array

};

public State getState()
{
        return mState;   
}

And use in Switch Statement

switch (mService.getState())
{
case Stopped:
case Paused:

    playPause.setBackgroundResource(R.drawable.selplay);
    break;

case Preparing:
case Playing:

    playPause.setBackgroundResource(R.drawable.selpause);
    break;    
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文