SlashTag SlashTag - 25 days ago 11
Java Question

Unreachable Statement with Break

So I had a previous question but realized I posted the wrong offending code. I've marked the offending statements below.

What I am trying to do is set the precedence for each of the operators with that switch statement.

Maybe someone could point me in the right direction.

Just as a note, I AM running JAVA 7 so String Switch will work.

Code

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


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

}

Answer

If you put a return, then the function returns before the break is executed and therefore the break will never be reached.

Instead you could use a variable that you set to a desired value and after the switch return that. Or just get rid of the break statements.