具有中断的无法访问的声明

Kyl*_*ley 2 java break switch-statement

所以我有一个上一个问题,但意识到我发布了错误的违规代码.我在下面标出了令人不快的陈述.

我要做的是为每个具有该switch语句的运算符设置优先级.

也许有人可以指出我正确的方向.

就像一张纸条,我在运行JAVA 7,因此String Switch可以工作.

opType.java

import java.io.*;

public final class opType {

   public static opType ADD = new opType( "Add" );
   public static opType SUB = new opType( "Sub" );
   public static opType MULT = new opType( "Mult" );
   public static opType DIV = new opType( "Div" );
   public static opType MOD = new opType( "Mod" );
   public static opType LPAR = new opType( "LParen" );
   public static opType RPAR = new opType( "RParen" );

   protected String name;

   private opType( String n )
   {
      name = n;
   }

   public String getName()
   {
      return name;
   }
Run Code Online (Sandbox Code Playgroud)

Operator.java

public class Operator extends Token {

    protected opType val;

    public boolean isOperator() { return true; }
    public boolean isOperand() { return false; }

    protected int getPrec()
    {

        switch(val.getName())
        {
            case "LParen": 
            {
                return 0;
                break; //unreachable
            }

            case "RParen": 
            {
                return 0;
                break; //unreachable
            }

            case "Mult":
            {
                return 1;
                break; //unreachable
            }
            case "Div": 
            {   
                return 1;
                break; //unreachable
            }
            case "Mod": 
            {   
                return 1;
                break; //unreachable
            }
            case "Add": 
            {   
                return 2;
                break; //unreachable
            }
            case "Sub": 
            {   
                return 2;
                break; //unreachable
            }
        }

            return 0;
    }

    public static int compare( Operator a, Operator b )
    {
        if( a.getPrec() == b.getPrec() )
            return 0;
        else if( a.getPrec() < b.getPrec() )
            return -1;
        else
            return 1;
    }

    public opType getVal() { return val; }

    public Operator( opType v ) { val = v; }

}
Run Code Online (Sandbox Code Playgroud)

Blu*_*lub 18

如果你输入a return,那么函数在break执行之前返回,因此break永远不会达到.

相反,您可以使用您设置为所需值的变量,并在切换后返回该变量.或者只是摆脱break陈述.


Jig*_*shi 6

你已经拥有return这将使break无法到达的