Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

>> REGISTER NOW TO START POSTING

# Thread: I need to make cases in a switch statement over certain ranges

1. ## I need to make cases in a switch statement over certain ranges

Here is the half code / half psuedocode of what I need to make.
I figured that I should use logical operators, but I couldn't find a way to make it work.

double gross;
double taxPercent;
```switch(gross)
{
case 0 to 300.00:
taxPercent = 0.10;
break;

case 300.01 to 400.00:
taxPercent = 0.12;
break;

case 400.01 to 500.00:
taxPercent = 0.15;
break;

case > 500.01:
taxPercent = 0.20;
break;

default:
System.out.println("ERROR! gross pay is less than 0");
break;
}```

I'd like to only use the switch statement for this.

2. ## Re: I need to make cases in a switch statement over certain ranges

The switch construct can only check for constants, if you want to check for a range, you should use if then structure instead.

3. ## Re: I need to make cases in a switch statement over certain ranges

Use an if/else-if chain.

I was going to offer the facetious alternative of having a *lot* of case parts. In fact, that won't fly. Switches are meant for when the thing being switched upon represents one out of a number of distinct possibilities. Integers are like that, as are characters: they are distinct. Floating point quantities like doubles represent things measured rather than counted - and they sort of "blend" into one another. In any case, you can't switch on a double in Java.

Of course, you could work in an int number of cents. Then I could make the facetious suggestion.

But your code suggests that you are really thinking of switching on something else: the "tax bracket". These are distinct and you can use them with switch/case providing you represent the various tax brackets as enums. I'm not sure this will completely free you from using an if/else-if chain though.