Results 1 to 5 of 5
Thread: using logical OR in switch
- 12-01-2011, 06:17 PM #1
Senior Member
- Join Date
- Dec 2011
- Posts
- 102
- Rep Power
- 0
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!
- 12-01-2011, 06:27 PM #2
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)How to Ask Questions the Smart Way
Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!
- 12-01-2011, 06:28 PM #3
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,427
- Blog Entries
- 7
- Rep Power
- 17
Re: using logical OR in switch
You can label more than one case label to a sequence of statements:
[code]
kind regards,Java 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.
Jos
edit: I'm the slowest old sod again ...When people rob a bank they get a penalty; when banks rob people they get a bonus.
- 12-01-2011, 06:37 PM #4
Senior Member
- Join Date
- Dec 2011
- Posts
- 102
- Rep Power
- 0
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!!
- 12-02-2011, 02:53 AM #5
Similar Threads
-
Logical problem in aplication
By lostmind in forum Advanced JavaReplies: 4Last Post: 12-24-2010, 10:21 PM -
if block with logical or
By Ranu in forum New To JavaReplies: 6Last Post: 07-01-2010, 08:11 AM -
Some Logical problem
By MuslimCoder in forum New To JavaReplies: 4Last Post: 03-01-2010, 08:12 AM -
Logical Gates
By lingz89 in forum New To JavaReplies: 1Last Post: 08-17-2009, 01:11 AM


2Likes
LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks