473,217 Members | 2,114 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,217 software developers and data experts.

Switch..Case Statement Question.

Can someone tell me if the following Switch...Case construct is valid?
I'm wanting to check for multiple values in the Case statement without
explicitly listing each values.
So for example, will case 1-35: work? If this would work, will it
consider all numbers between 1 and 35 inclusive of 1 and 35? Please let
me know if the following will work below:

switch(state){
case 1-35:
case 37:
do something_1;
break;
case 36:
do something_2;
break;
case 38-50:
do something_3;
break;
}
Thank you.
Andy.

Jul 23 '05 #1
21 7586
Andy wrote on 28 feb 2005 in comp.lang.javascript:
Can someone tell me if the following Switch...Case construct is valid?
I'm wanting to check for multiple values in the Case statement without
explicitly listing each values.
So for example, will case 1-35: work? If this would work, will it
consider all numbers between 1 and 35 inclusive of 1 and 35? Please let
me know if the following will work below:
did you test it yourself? If not why not?
switch(state){
case 1-35:
case 37:
do something_1;
break;


this part will execute if "state" is -34 or 37,
because 1-35 is 34, I think.

But please test it yourself.
--
Evertjan.
The Netherlands.
(Replace all crosses with dots in my emailaddress)

Jul 23 '05 #2
Lee
Andy said:

Can someone tell me if the following Switch...Case construct is valid?
I'm wanting to check for multiple values in the Case statement without
explicitly listing each values.
So for example, will case 1-35: work? If this would work, will it
consider all numbers between 1 and 35 inclusive of 1 and 35? Please let
me know if the following will work below:

switch(state){
case 1-35:
case 37:
do something_1;
break;
case 36:
do something_2;
break;
case 38-50:
do something_3;
break;
}


With less effort and much less wait time, you could have just tested
your sample code yourself. Your first case will match any state that
equals your index value of -34 (1-35).

Jul 23 '05 #3
I apologize for not having tested myself and wasted your time. Do you
or anyone else knows of a way to check for multiple values without
stating each one like if I'd like to check all values from 1 through 35
how would i do it?

Any help will be appreciated.

Jul 23 '05 #4
Andy wrote:
Can someone tell me if the following Switch...Case construct is valid?
No.
I'm wanting to check for multiple values in the Case statement without
explicitly listing each values.


You cannot. The expression after the case keyword is compared for
strict equality (===) with the expression in the switch statement. In
other words,

switch(2) {
case '2': /* This statement list will not be evaluated. */
}

the statement list for case '2' will not be evaluated because the
expressions do not evaluate to the same type (one is a number, the
other is a string).

You have little choice but to use an if statement.

if(((1 <= state) && (35 >= state)) || (37 == state)) {
/* Between 1 and 35 (inclusive) or is 37 */
something_1();
} else if(36 == state) {
/* Is 36 */
something_2();
} else if((38 <= state) && (50 >= state)) {
/* Between 38 and 50 (inclusive) */
something_3();
}

[snip]

Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #5
Andy wrote on 28 feb 2005 in comp.lang.javascript:
I apologize for not having tested myself and wasted your time. Do you
or anyone else knows of a way to check for multiple values without
stating each one like if I'd like to check all values from 1 through 35
how would i do it?

Please do not use usenet as a form of email. you are replying to many
here, so quote relevant part of the mail you answer on. Remember
netiquette.

Now "I" have to quote from your old posting:switch(state){
case 1-35:
case 37:
do something_1;
break;
case 36:
do something_2;
break;
case 38-50:
do something_3;
break;

You could do:

state = 20;
switch(true){
case state>=1&&state<=35:
case state==37:
do something_1;
break;
case state==36:
do something_2;
break;
case state>=38&&state<=50:
do something_3;
break;
case default:
alert('default')
}

This however in my view defies usefulness of switch().
anyway if-else is much more robust:

state = 20;
if ((state>=1&&state<=35)||state==37){
do something_1
else if (state==36)
do something_2
else if (state>=38&&state<=50)
do something_3
else
alert('default');

[not tested]

--
Evertjan.
The Netherlands.
(Replace all crosses with dots in my emailaddress)

Jul 23 '05 #6
Andy wrote:
I apologize for not having tested myself and wasted your time. Do you
or anyone else knows of a way to check for multiple values without
stating each one like if I'd like to check all values from 1 through 35
how would i do it?

Any help will be appreciated.

This is where the "greater than or equal to" and "less than or equal to"
operators come in handy. For instance, ">=1 && <=35" is between one and
thirty-five.
Jul 23 '05 #7
You can also try

switch(true){

case(val>1 && val<35): do something;break;
case(val>=35 && val <53):do something;break;

Jul 23 '05 #8
bumbleguppy wrote on 05 mrt 2005 in comp.lang.javascript:
You can also try

switch(true){

case(val>1 && val<35): do something;break;
case(val>=35 && val <53):do something;break;


[please quote, usenet is not email]

is the above really more useful than:

if (val>1 && val<35) do_something;
if (val>=35 && val<53) do_something;

?

--
Evertjan.
The Netherlands.
(Replace all crosses with dots in my emailaddress)

Jul 23 '05 #9
rh
Evertjan. wrote:
bumbleguppy wrote on 05 mrt 2005 in comp.lang.javascript:
You can also try

switch(true){

case(val>1 && val<35): do something;break;
case(val>=35 && val <53):do something;break;


[please quote, usenet is not email]

is the above really more useful than:

if (val>1 && val<35) do_something;
if (val>=35 && val<53) do_something;

?


I'd have to say "No", because the former is syntactically (block)
deficient. ;-)

However, the "switch/case" idiom can be more useful, or at least more
appropriate to use, in some circumstances because of the nature of the
structural encapsulation it provides for a specific filtering task.

The choice shouldn't have any effect on the result of the execution,
but it can have a marked effect on the readability and maintainability
of the code.

../rh

Jul 23 '05 #10
Welcome to 2005 guy.

I don't know what archaic usenet application you are using to view this
thread, but I however am writing this reply in a text box in a webpage.
A Google webpage.

Why would I want to load an html page with the same quoted statemaents
ad naseum when, in my web browser, I can scoll up to see the relevent
subject material?

You remind me of the playground rules in tag. No electricity except in
freeze tag. No tagbacks.

You saw my post. You understood the meaning. Save your sophomoric
nerdish and arbitrary instructions to the next newbie that wants to
"fit in" with the geeks.

Jul 23 '05 #11
bumbleguppy wrote:
Welcome to 2005 guy.

I don't know what archaic usenet application you are using to view this
thread, but I however am writing this reply in a text box in a webpage.
A Google webpage.
A Google webpage that is not a Usenet application but an attempt at a
web-based application for interfacing to Usenet.
Why would I want to load an html page with the same quoted statemaents
ad naseum when, in my web browser, I can scoll up to see the relevent
subject material?


Are you actually stupid enough to believe that rubbish that you spout?

--
Randy
comp.lang.javascript FAQ - http://jibbering.com/faq & newsgroup weekly
Jul 23 '05 #12
bumbleguppy wrote:
Welcome to 2005 guy.

I don't know what archaic usenet application you are
using to view this thread, but I however am
Whatever _you_ may be doing is irrelevant. Usenet is a one-to-many
communication medium where the needs/wishes/interest of the many
outweigh all personal preferences. Saving yourself a little effort in
exchange for wasting the time of hundreds or thousands of others is
objectionable and likely to be considered rude.
writing this reply in a text box in a
webpage. A Google webpage.
Recent changes in google's Usenet interface have rendered it on a par
with the very worst providers of web-based access to Usenet
(Forum4designers.com) and the only reasonable advice now possible is to
abandon using google groups in favour of some superior web-based
provider or (preferably) access Usenet directly through an NTTP server
(as provided by any ISP worthy of the name) using real newsreader
software.
Why would I want to load an html page
comp.lang.javascirpt is a plain text _only_ newsgroup.
with the same quoted statemaents
ad naseum when,
The convention is to _only_ quote the material that is being respond to,
and trim the rest. It is done to provide a context for the response.
in my web browser, I can scoll up to see
the relevent subject material?
What ever you can do says nothing bout what the many who read your posts
can do (or what they would prefer to do). You (alone) will never be the
arbiter of what it correct.
You remind me of the playground rules in tag. No
electricity except in freeze tag. No tagbacks.
Games, and many other things, work best when everyone plays by the same
rules. The 'rules', the conventions for Usenet posting, have been around
for a long time (more than 20 years), evolved to suite the medium, and
can be found by reading the groups FAQ (the reading of which is a
pre-requisite for participation in any technical Usenet group that
provides a FAQ).
You saw my post. You understood the meaning. Save
your sophomoric nerdish and arbitrary instructions to
the next newbie that wants to "fit in" with the geeks.


Are you inviting that active hostility of regulars on this group?

Richard.
Jul 23 '05 #13
rh wrote:
Evertjan. wrote:
bumbleguppy wrote: <snip>
switch(true){
case(val>1 && val<35): do something;break;
case(val>=35 && val <53):do something;break;
<snip> is the above really more useful than:

if (val>1 && val<35) do_something;
if (val>=35 && val<53) do_something;

?


I'd have to say "No", because the former is syntactically
(block) deficient. ;-)

<snip>

To be honest I find the former superior, but only because of one
omission in the latter; there should be an - else - in front of the
second - if - statement. The conditions are mutually exclusive and there
is no reason to evaluate the second after the first has evaluated to -
true.

Range testing in - if/else if/else - blocks seems more readable than
controlling a - switch - from a numeric or boolean literal and then
evaluating expressions in the - case - clauses (useful as that facility
may be in other contexts).

Richard.
Jul 23 '05 #14
Evertjan. wrote:
bumbleguppy wrote on 05 mrt 2005 in comp.lang.javascript:

You can also try

switch(true){

case(val>1 && val<35): do something;break;
case(val>=35 && val <53):do something;break;

[please quote, usenet is not email]

is the above really more useful than:

if (val>1 && val<35) do_something;
if (val>=35 && val<53) do_something;


Actually, yes. You're missing an 'else'.

---
John W. Kennedy
"Those in the seat of power oft forget their failings and seek only the
obeisance of others! Thus is bad government born! Hold in your heart
that you and the people are one, human beings all, and good government
shall arise of its own accord! Such is the path of virtue!"
-- Kazuo Koike. "Lone Wolf and Cub: Thirteen Strings" (tr. Dana Lewis)
Jul 23 '05 #15
John W. Kennedy wrote on 06 mrt 2005 in comp.lang.javascript:
Evertjan. wrote:
bumbleguppy wrote on 05 mrt 2005 in comp.lang.javascript:

You can also try

switch(true){

case(val>1 && val<35): do something;break;
case(val>=35 && val <53):do something;break;

[please quote, usenet is not email]

is the above really more useful than:

if (val>1 && val<35) do_something;
if (val>=35 && val<53) do_something;


Actually, yes. You're missing an 'else'.


That being my [inconsequental in this example] mistake
does not per se make it less useful then the switch(true)
--
Evertjan.
The Netherlands.
(Replace all crosses with dots in my emailaddress)

Jul 23 '05 #16
Lee
bumbleguppy said:

Welcome to 2005 guy.
You saw my post. You understood the meaning. Save your sophomoric
nerdish and arbitrary instructions to the next newbie that wants to
"fit in" with the geeks.


Don't be so quick to rule out the possibility that you lack the
experience to understand why the request is reasonable. That's
a really good way to make yourself appear to be spectacularly
ignorant.

Insulting people for making a request whose value you fail to
understand makes you look that much worse.

Jul 23 '05 #17
rh
Richard Cornford wrote:

<..>
Range testing in - if/else if/else - blocks seems more readable than
controlling a - switch - from a numeric or boolean literal and then
evaluating expressions in the - case - clauses (useful as that facility may be in other contexts).


So it would seem, although I think that's in large part due to lack of
some Javascript switch/case facility that's seen in other languages.

In the greater scheme of things, I tend to view the distinction between
switch/case and if/else as the former being more for conditioning
(i.e., setup) and the latter more for program flow control. Of course,
if/else is always favoured and appropriate when the set of cases to be
distinguished is small.

Not a perfect substitute, but perhaps helpful in the context of numeric
range filtering, would be something like:

<script type="text/javascript">

Number.prototype.inRng = function( str ) {
var testSet = str.split( "," );
for ( var k = 0; k < testSet.length; k++ ) {
var rng = testSet[ k ]
.replace( /(\d|y)\s*-\s*([+-]?(\d|I))/g, "$1#$2" )
.split( "#" );
if ( typeof rng[ 1 ] == "undefined" ) rng[ 1 ] = rng[ 0 ];
if ( this >= rng[ 0 ] && this <= rng[ 1 ] ) return true;
}
return false;
}

var z = 33;

switch ( true ) {

case z.inRng( '1-35, 37' ) :
//..
break;

case z == 36 :
//..
break;

case z.inRng( '38-50' ) :
//..
break;

default :
//..
}
</script>

../rh

Jul 23 '05 #18
rh wrote on 06 mrt 2005 in comp.lang.javascript:
Number.prototype.inRng = function( str ) {


Try this:

<script type="text/javascript">
var myCase = 'myCase';
var mydo = 'mydo';
var myDefault = 'myDefault';
var res,a;

function mySwitch(){
var base = mySwitch.arguments[0]
for (var i=1;i<mySwitch.arguments.length;i++){
a = mySwitch.arguments[i]
if(i==0)var val=a
else if (a==myCase)res=false
else if ((a==mydo&&res)||a==myDefault){
eval(mySwitch.arguments[++i])
return }
else if (!res){
if (/\d+\-\d+/.test(a))
res = (base>=1*a.replace(/-\d+/,''))&&
(base<=1*a.replace(/\d+-/,''))
else
res = (base==a)
}
}
}
mySwitch(

6,

myCase,2,3,4,
mydo,"alert('TwoThreeFour')",
myCase,"5-7",8,
mydo,"alert('FiveToEight')",
myCase,9,100,
mydo,"alert('NineOrHundred')",
myDefault,
"alert('NoneOfThem')"
)

</script>

--
Evertjan.
The Netherlands.
(Replace all crosses with dots in my emailaddress)

Jul 23 '05 #19
rh
Evertjan. wrote:
rh wrote on 06 mrt 2005 in comp.lang.javascript:
Number.prototype.inRng = function( str ) {
Try this:


<..>

mySwitch(

6,

myCase,2,3,4,
mydo,"alert('TwoThreeFour')",
myCase,"5-7",8,
mydo,"alert('FiveToEight')",
myCase,9,100,
mydo,"alert('NineOrHundred')",
myDefault,
"alert('NoneOfThem')"
)


Well, you'll have to be given points for a adopting an inventive and
novel approach, but I don't think I want to go there.

Note that as soon as you call the "mySwitch" function, you've lost the
current execution context. That means that if you want to do something
that's actually useful in a "mydo", such as test or assign to a local
variable from the original context, you're snookered.

../rh

Jul 23 '05 #20
Evertjan. wrote:
John W. Kennedy wrote on 06 mrt 2005 in comp.lang.javascript:

Evertjan. wrote:
bumbleguppy wrote on 05 mrt 2005 in comp.lang.javascript:

You can also try

switch(true){

case(val>1 && val<35): do something;break;
case(val>=35 && val <53):do something;break;

[please quote, usenet is not email]

is the above really more useful than:

if (val>1 && val<35) do_something;
if (val>=35 && val<53) do_something;


Actually, yes. You're missing an 'else'.

That being my [inconsequental in this example] mistake
does not per se make it less useful then the switch(true)


I once saw, in the real world, in a production program, 100 (yes,
literally 100) mutually exclusive cases IF'ed without a single ELSE.

---
John W. Kennedy
"Those in the seat of power oft forget their failings and seek only the
obeisance of others! Thus is bad government born! Hold in your heart
that you and the people are one, human beings all, and good government
shall arise of its own accord! Such is the path of virtue!"
-- Kazuo Koike. "Lone Wolf and Cub: Thirteen Strings" (tr. Dana Lewis)
Jul 23 '05 #21
JRS: In article <d0*********@drn.newsguy.com>, dated Sun, 6 Mar 2005
09:33:37, seen in news:comp.lang.javascript, Lee
<RE**************@cox.net> posted :
bumbleguppy said:

Welcome to 2005 guy.

You saw my post. You understood the meaning. Save your sophomoric
nerdish and arbitrary instructions to the next newbie that wants to
"fit in" with the geeks.


Don't be so quick to rule out the possibility that you lack the
experience to understand why the request is reasonable. That's
a really good way to make yourself appear to be spectacularly
ignorant.

Insulting people for making a request whose value you fail to
understand makes you look that much worse.


With the consequence, which probably does need to be spelt out, that the
regular experts will ignore the questions of such posters, confining
themselves to correcting the errors that they make in their responses,
if any, to others.

Whatever suits the convenience of the expert regulars increases the
chances of getting good answers.

--
John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 MIME
Web <URL:http://www.uwasa.fi/~ts/http/tsfaq.html> -> Timo Salmi: Usenet Q&A.
Web <URL:http://www.merlyn.demon.co.uk/news-use.htm> : about usage of News.
No Encoding. Quotes before replies. Snip well. Write clearly. Don't Mail News.
Jul 23 '05 #22

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: Aristotelis E. Charalampakis | last post by:
Hi all, this is a newbie question :-) I was wondering if there was a way to use the switch statement in a manner that each case statement includes more that a simple value. i.e.: switch (...
35
by: Thomas Matthews | last post by:
Hi, My son is writing a program to move a character. He is using the numbers on the keypad to indicate the direction of movement: 7 8 9 4 5 6 1 2 3 Each number has a direction except...
18
by: swaroophr | last post by:
Which of switch statement and if-else statement takes less time to execute?
3
by: pgraeve | last post by:
I am a convert from VB to C# so bear with me on this "conversion" question C# switch statement seems to be the closest relative to VB's Select Case. I used VB's Select Case statement liberally. ...
2
by: Cathleen C via DotNetMonster.com | last post by:
I'm a semi-beginner with c# and am having a problem effectively implementing a switch statement. I've created an asp.net app that runs a report depending on which item was selected from a drop...
7
by: priyanka | last post by:
Hi there, I had a question. Is there any way of testing a string value in a switch statement. I have about 50 string values that can be in a string variable. I tried cheking them with the if...
13
by: Satya | last post by:
Hi everyone, This is the first time iam posting excuse me if iam making any mistake. My question is iam using a switch case statement in which i have around 100 case statements to compare. so...
0
by: veera ravala | last post by:
ServiceNow is a powerful cloud-based platform that offers a wide range of services to help organizations manage their workflows, operations, and IT services more efficiently. At its core, ServiceNow...
0
by: VivesProcSPL | last post by:
Obviously, one of the original purposes of SQL is to make data query processing easy. The language uses many English-like terms and syntax in an effort to make it easy to learn, particularly for...
0
by: jianzs | last post by:
Introduction Cloud-native applications are conventionally identified as those designed and nurtured on cloud infrastructure. Such applications, rooted in cloud technologies, skillfully benefit from...
0
by: mar23 | last post by:
Here's the situation. I have a form called frmDiceInventory with subform called subfrmDice. The subform's control source is linked to a query called qryDiceInventory. I've been trying to pick up the...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
2
by: jimatqsi | last post by:
The boss wants the word "CONFIDENTIAL" overlaying certain reports. He wants it large, slanted across the page, on every page, very light gray, outlined letters, not block letters. I thought Word Art...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.