Skip to content
Advertisement

Can you invert a switch in java?

Is there a way to invert a switch for example switch (!(x))? I’m writing a program and I only want the user to be able to input certain letters. If they input an invalid letter, they would have to input it again. I’m trying to use a switch for this avoiding doing something like

switch(x)    
{    
   case a : case b: case c: case d: etc etc    
}

because the number of valid inputs are much smaller then the number of invalid ones so I would have like 20 cases.

Advertisement

Answer

You can do

switch(x)
{
case 'x' : case 'y': case 'z': //valid; 
break;
default: //invalid;
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement