using logical OR in switch
Hi,
I've been trying to use "||" in switch, but it won't let me.
I'm pretty sure there must be a way, coz if i want the same result for e or E, it's just weird to copy paste everything again in a new case.
here's a part of my program:
switch (user_choice.charAt(0)) {
case 'a' : JOptionPane.showMessageDialog(null ,num1 + " + " + num2 + " = " + (num1+num2));
break;
case 'A' : JOptionPane.showMessageDialog(null ,num1 + " + " + num2 + " = " + (num1+num2));
break;
case 'm' : JOptionPane.showMessageDialog(null ,num1 + " * " + num2 + " = " + (num1*num2));
break;
case 'M' : JOptionPane.showMessageDialog(null ,num1 + " * " + num2 + " = " + (num1*num2));
break;
default : JOptionPane.showMessageDialog (null,"Unknown command, sorry!\n");
if there is a way.. i'm dying to know :|
TNX!
Re: using logical OR in switch
Just let the case fall through:
case 'A':
case 'a':
//whatever
break;
This is covered in the basic switch tutorial, which is the first hit for googling "java switch": The switch Statement (The Java™ Tutorials > Learning the Java Language > Language Basics)
Re: using logical OR in switch
You can label more than one case label to a sequence of statements:
[code]
Code:
switch (user_choice.charAt(0)) {
case 'A':
case 'a': JOptionPane.showMessageDialog(null ,num1 + " + " + num2 + " = " + (num1+num2));
break;
case 'M':
case 'm': JOptionPane.showMessageDialog(null ,num1 + " * " + num2 + " = " + (num1*num2));
break;
// etc.
kind regards,
Jos
edit: I'm the slowest old sod again ...
Re: using logical OR in switch
Oh,
Great idea!
It's funny he hasn't showed us that in class... well.. that's academy.. u should learn 90% of the stuff urself.................. (or in forums xD)
Thank you both!!
Re: using logical OR in switch
Quote:
Originally Posted by
Mapisto
u should learn 90% of the stuff urself..................
Unlike spelling and grammar which is taught in school.