Tuesday, March 13, 2012

Switch / case statements

Been a while since I did a switch statement, and that was in VB.
Error I'm getting is...
Control cannot fall through from one case label ('case 14:') to another
Well, not just case 14, but all of them.
Here's the sample...

publicbool checkMe(ArrayList myArray,int myInt){

switch (myInt) {

case 3 :

if(System.Convert.ToInt32( myArray[0] )== 0 &&

System.Convert.ToInt32( myArray[1]) == 1 )

{

myArray[1] = 0;

myArray[3] = 0;

myArray[0] = 1;

pNum = 3;

tempAL = myArray;

printArray(tempAL);

bSuccess =true;

break;

}

if( System.Convert.ToInt32( myArray[5] ) == 0 &&

System.Convert.ToInt32( myArray[4] ) == 1 )

{

myArray[4] = 0;

myArray[3] = 0;

myArray[5] = 1;

pNum = 3;

tempAL = myArray;

printArray(tempAL);

bSuccess =true;

break;

}

case 5 :

if( System.Convert.ToInt32( myArray[0] ) == 0 &&

System.Convert.ToInt32( myArray[2] ) == 1 )

{

myArray[2] = 0;

myArray[5] = 0;

myArray[0] = 1;

pNum = 5;

tempAL = myArray;

printArray(tempAL);

bSuccess =true;

break;

}

if( System.Convert.ToInt32( myArray[3] ) == 0 &&

System.Convert.ToInt32( myArray[4] ) == 1 )

{

myArray[4] = 0;

myArray[5] = 0;

myArray[3] = 1;

pNum = 5;

tempAL = myArray;

printArray(tempAL);

bSuccess =true;

break;

}

default :

{

bSuccess =false;

}


}

So, what's the deal?
Thanks,
Zath

That's because C# requires a break statement after every case statement (at least ones with code in them), and yours are within conditionals. Here's your code fixed up:
public bool checkMe(ArrayList myArray, int myInt)
{
switch ( myInt )
{
case 3:
if ( System.Convert.ToInt32(myArray[0]) == 0 &&
System.Convert.ToInt32(myArray[1]) == 1 )
{
myArray[1] = 0;
myArray[3] = 0;
myArray[0] = 1;

pNum = 3;
tempAL = myArray;
printArray(tempAL);

bSuccess = true;
break;
}

if ( System.Convert.ToInt32(myArray[5]) == 0 &&
System.Convert.ToInt32(myArray[4]) == 1 )
{
myArray[4] = 0;
myArray[3] = 0;
myArray[5] = 1;

pNum = 3;
tempAL = myArray;
printArray(tempAL);

bSuccess = true;

break;
}

break;
case 5:
if ( System.Convert.ToInt32(myArray[0]) == 0 &&
System.Convert.ToInt32(myArray[2]) == 1 )
{
myArray[2] = 0;
myArray[5] = 0;
myArray[0] = 1;

pNum = 5;
tempAL = myArray;
printArray(tempAL);

bSuccess = true;

break;
}


if ( System.Convert.ToInt32(myArray[3]) == 0 &&
System.Convert.ToInt32(myArray[4]) == 1 )

{
myArray[4] = 0;
myArray[5] = 0;
myArray[3] = 1;

pNum = 5;
tempAL = myArray;
printArray(tempAL);
bSuccess = true;

break;
}

break;
default :
bSuccess = false;

break;
} // end of switch statement
} // end of method


You could do something like this and it would work:
switch ( someValue )
{
case 0:
case 1:
// do something
break;
case 2:
// do something
break;
default:
break;
}
NC...


Thanks, that did the trick.
Just when you think you know all the syntaxBig Smile [:D]
Zath

0 comments:

Post a Comment