Testing for a Range of Values in a Switch Statement

O

OutdoorGuy

Greetings,

I was wondering if it is possible to test for a range of values in a
"Switch" statement? I have the following code, but it is generating an
error when I attempt to compile it. Any suggestions?

Thanks in advance!

public static String getMessageSwitch(int score)
{
String message;
switch (score)
{
case 90 - 100:
message = "an 'A'";
break;
case 80 - 90:
message = "a 'B'";
break;
case 70 - 80:
message = "a 'C'";
break;
case 60 - 70:
message = "a 'D'";
break;
case 0 - 59:
message = "an 'F'";
break;
default:
message = ":an error occurred";
break;
} // End of "Switch" block
return message;
 
A

Alan Pretre

OutdoorGuy said:
I was wondering if it is possible to test for a range of values in a
"Switch" statement? I have the following code, but it is generating an
error when I attempt to compile it. Any suggestions?

No, unfortunately that syntax is not allowed in C#. You'll have to use
If/Elseif's to implement.

PS: Your ranges are overlapping in each case...
 
S

Samuel R. Neff

In this particular case you can use a little simple math to achieve
the same result.

public static String getMessageSwitch(int score)
{
String message;
switch ((int)Math.Floor(score/10))
{
case 10:
case 9:
message = "an 'A'";
break;
case 8:
message = "a 'B'";
break;
case 7:
message = "a 'C'";
break;
case 6:
message = "a 'D'";
break;
default:
message = "an 'F'";
break;
} // End of "Switch" block
return message;
}


HTH,

Sam
 
O

OutdoorGuy

Thanks. By the way, I'm assuming you can't use the Less Than (<) or
Greater Than (>) symbols in a Switch statement either. Am I correct?
 
A

Alan Pretre

OutdoorGuy said:
Thanks. By the way, I'm assuming you can't use the Less Than (<) or
Greater Than (>) symbols in a Switch statement either. Am I correct?

That's right, unfortunately.

I have written several compilers in my lifetime. One thing I implemented
was a computable case. It allowed arbitrary expression evaluation in the
cases, even function calls, etc. That's very handy.

-- Alan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top