枚举不适用于switch语句

时间:2014-09-26 07:52:30

标签: java enums

我正在尝试切换状态。我首先在START_STATE开始。然后,我提示用户是否转到FAIL_STATE或GO_STATE。然而,似乎他们是否输入" go" (对于GO_STATE)失败(对于FAIL_STATE),其他任何一种情况都没有被激活。这个问题的解决方案是什么?

import java.util.*;

public class dfa {
      static State state;


public enum State 
   {
        START_STATE,
         GO_STATE,
         FAIL_STATE,
         };


dfa(State state)
 { state = this.state;}

/**
 * @param args
 */
public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    String line;

    state = State.START_STATE;   
        switch(state)
            {
            case START_STATE:

                System.out.print("In start state \n ");
                System.out.println("Which state you want to go to? \n");
                line = input.next();
                if(line.equals("go"))
                {
                    state = State.GO_STATE;
                    System.out.print(" Go hello");
                }
                else if(line.equals("fail"))
                {
                    state = State.FAIL_STATE;
                System.out.println(" Fail hello ");
                }
                 break;
                case FAIL_STATE:  
                System.out.println("fail state");
                break;
                case GO_STATE:
                System.out.println("go state");
               break;

            default:
                System.out.println("Default");
                break;
            }


    System.out.println("made it here");





    }

}

输出:

(When "go" is typed)
Go hello 
made it here

(When "fail" is typed)
Fail hello 
made it here

3 个答案:

答案 0 :(得分:1)

您的case START_STATE没有break。然后它将永远转到下一个案例,女巫case FAIL_STATE:女巫有break

您的switch-case应遵循此订单。

switch(condition){
    case con1:
     // do something
    break;
    case con2:
     // do something
    break;
    default:
    // do something
    break;        

}

答案 1 :(得分:0)

对于START_STATE:

,您只是忘记了break
case START_STATE:
    System.out.print("In start state \n ");
    System.out.println("Which state you want to go to? \n");
    line = input.next();
    if(line.equals("go")) {
        state = State.GO_STATE;
        System.out.print(" Go hello");
    } else if(line.equals("fail")) {
        state = State.FAIL_STATE;
        System.out.println(" Fail hello ");
    }
    break; // <-- here

答案 2 :(得分:0)

您在break的末尾缺少case START_STATE声明,因此它会落到下一个case

case START_STATE:
    System.out.print("In start state \n ");
    System.out.println("Which state you want to go to? \n");
    line = input.next();
    if(line.equals("go"))
    {
        state = State.GO_STATE;
        System.out.print(" Go hello");
    }
    else if(line.equals("fail"))
    {
        state = State.FAIL_STATE;
        System.out.println(" Fail hello ");
    }
    break; // Missing from OP