Hi guys

I have part of the code that looks something like this:

if(c1=='a')
    		  myStack.push(c1);
    	  else if(c1=='b')
    		  myStack.push(c1);
    	  else if(c1=='c')
    		  myStack.push(c1);

I just want to ask is there any way to rewrite this code, to make it more compact
something like

if(c1==('(a'||'b'||'c') // I know this doesn't work

but I'm looking something that would be nice and short.

You can OR the expressions together like this
c1=='a' || c1 == 'b' ...

but if you want a very short version with many tests like that you can use some geeky construct like
"abc".indexOf(c1) >= 0

you were close tho, you can use "||" which is OR , "|" would work too but "||" is more efficient, because if the first condition is true then it knows it makes no diference to check the second, where you got it wrong is you gotta give full conditions on each side of the OR, so :

if(c1=='a' || c1=='b' || c1=='c')myStack.push(c1);

if you had to execute diferent code in each "else if" of the orginal code, you could still compact it with ternary operators "(condition?truestatement:falsestatement);"

like this :

(c1=='a' ? myStack.push(c1) : (c1=='b' ? myOtherStack.push(c1) : (c1=='c' ? myThirdStack.push(c1) : "" ) ) );

please note that im not entirely sure about the "" part where it doesnt meet any requirement, i believe ternary operators will ask for each of its outcomes to return the same type of value, so whatever push returns you would need to return that , in case of a bool , put false instead of ""... etc.

but that was just a little extra anyways ;P enjoy

"abc".indexOf(c1) >= 0

i like that ! lol, smart

oh thank's a lot guys!!!! it is very helpful!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.