program tip

스위치 문과 함께 열거 형을 사용하는 Java

radiobox 2020. 8. 16. 20:05
반응형

스위치 문과 함께 열거 형을 사용하는 Java


나는이 질문과 비슷한 다양한 Q & A를 보았지만 해결책을 찾지 못했습니다.

내가 가진 것은 TV 가이드를 보는 다양한 방법을 나타내는 열거 형입니다.

NDroid Application클래스에서

static enum guideView {
    GUIDE_VIEW_SEVEN_DAY,
    GUIDE_VIEW_NOW_SHOWING,
    GUIDE_VIEW_ALL_TIMESLOTS
}

... 사용자가 뷰를 변경하면 이벤트 핸들러 int가 0-2에서 수신하고 다음과 같이하고 싶습니다 ...

Android Activity onClick(DialogInterface dialog, 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클래스에 정의되어 있고 스위치를 원하지 않는 코드는 Activity. 열거 형은 여러 활동에서 액세스해야하므로 정적입니다.


누락 된 부분은 정수에서 유형 안전 열거 형으로 변환하는 것입니다. Java는 자동으로 수행하지 않습니다. 이에 대해 몇 가지 방법이 있습니다.

  1. 형식이 안전한 열거 형 대신 정적 최종 정수 목록을 사용하고받은 int 값을 켭니다 (이는 Java 5 이전 접근 방식입니다).
  2. 지정된 id 값 ( heneryville에 설명 된대로 ) 또는 열거 형 값의 서수 값을 켭니다 . guideView.GUIDE_VIEW_SEVEN_DAY.ordinal()
  3. int 값이 나타내는 열거 형 값을 확인한 다음 열거 형 값을 켭니다.

    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;
        }
    }
    

    valueOf정수 값을 인수로 사용하여 적절한 열거 형 값을 확인하고 경계 검사를 중앙 집중화 할 수 있는 사용자 지정 구현 을 작성하는 것이 더 유용하거나 오류가 적을 수 있습니다.


whichViewGuideView Enum의 객체 인 경우 다음이 잘 작동합니다. 이후 상수에 대한 한정자가 없습니다 case.

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

열거 형은 보유한 것과 같이 케이스 레이블 내에서 정규화되어서는 안되며 NDroid.guideView.GUIDE_VIEW_SEVEN_DAY, 대신 자격을 제거하고 사용해야합니다.GUIDE_VIEW_SEVEN_DAY


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;

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.


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

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.


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;    
}

참고URL : https://stackoverflow.com/questions/8108980/java-using-enum-with-switch-statement

반응형