Discussion Locked

Java switch statement

0 helpful
3 replies
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.

Is it possible to use relational operators in the case: section of a Java switch
eg
switch (guess)
case (>number):...
etc

I know the above doesn't work, but that's the sort of thing I need. I need to compare the variable in the switch (guess) with a computer generated random number, and report whether the guess is too high, too low, or correct (it's a simple guessing game...pick a number between 1 and 1000 etc).

Thanks,
M.R.Chambers

3 replies

by paul field

Afraid not... 'switch' evaluates an expression and then checks for a 'case' that *equals* the result.

The expression must be of type: char, byte, short, or int.
The case labels must contain constant expressions.

You'll need to use 'if' statements:

if (guess < number) {
// guess was too low
} else if (guess > number) {
// guess was too high
} else {
// guess was correct
}

by m.r.chambers

I didn't think it would work, but I wanted to avoid using nested IFs - that's waht I'm using at the moment and wanted to see if I could change (I'm only just starting out in Java). Anyway, thanks for the answer. Cya.

M.R.Chambers

This discussion is closed to new replies.