Is there anyway to use greater than or less than in Switch statements?
Like this
switch(variable){
case <0:
do stuff;
break;
default:
break;
}
Thanks for any help
Printable View
Is there anyway to use greater than or less than in Switch statements?
Like this
switch(variable){
case <0:
do stuff;
break;
default:
break;
}
Thanks for any help
thats crazy, just use an if-else statement.
hi,
as far as I know only constants are in switch-case-statements allowed. I would also go for if-else
I did use if else statements at first and it worked fine, the only problem is in my class they use this thing called Checkstyle and the more if else statements I have it gives a Cyclomatic Complexity error. Has anyone here used Checkstyle? Checkstyle is alot more forgiving on Switch Statements.
hm, never herd of that error. have u some code beside that code above?
dont know if it will help but here is a switch statement that I have in a working app
Code:// THE SWITCH BELOW WILL GIVE A DISCOUNT FOR THE NUMBER OF YEARS NO CLAIMS DISCOUNT
switch (Integer.parseInt(txtYears.getText())) {
case 1:
premium = premium * 0.80;
break;
case 2:
premium = premium * 0.70;
break;
case 3:
premium = premium * 0.60;
break;
case 4:
premium = premium * 0.50;
break;
case 5:
premium = premium * 0.45;
break;
// 2 years no claims bonus case 6
case 6:
premium = premium * 0.41;
break;
case 7:
premium = premium * 0.40;
break;
default:
premium = premium ;
}
I would put the lookup into a static HashMap<Integer, Double> in this way:This has the advantage of keeping the lookup values at the top (or bottom) of the class, easy to find if the business rules change.Code:static Map<Integer, Double> factors = new HashMap<Integer, Double>();
factors.put(1, 0.80);
factors.put(2, 0.70);
factors.put(3, 0.60);
... ...
:
:
premium *= factors.get(Integer.parseInt(txtYears.getText()));
Of course, if frequent changes are anticipated, the data should be read from a database.
db
Hi! I was looking for the answer to this myself, and I think I discovered an easy way as I was reading.
add an int.
int i;
if(var1>var2) i = 1;
if(var1=var2 i = 0;
if(var1<var2) i = -1;
switch (i);
{
case -1:
do stuff;
break;
case 0:
do stuff;
break;
case 1:
do stuff;
break;
}
If it's just a few small ranges, you could take advantage of the fact that execution "falls through" to the next case whenever you omit a break statement:
If there are many large ranges, an if-else statement would probably be better. Switches can be more efficient, but they are harder to write and maintain, and therefore more likely to introduce bugs. I only use large switches in generated code.Code:switch(someInteger) {
case 1:
case 2:
case 3:
// do stuff
break;
case 4:
case 5:
case 6:
// do stuff
break;
}