File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes If-Else to a Switch Statement Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "If-Else to a Switch Statement" Watch "If-Else to a Switch Statement" New topic

If-Else to a Switch Statement

Paul Hobson

Joined: Oct 29, 2003
Posts: 4
I'm trying to rewrite these If-Else Statements into a Switch statement. the problem is i have the >= in the If-Else and everywhere i look. the switch statement corresponds to ==.
char G;
if (N >= 90)
G = 'A';
else if (N>=80)
G = 'B';
else if (N>=70)
G = 'C';
else if (N>=60)
G = 'D';
G = 'F';
Dirk Schreckmann

Joined: Dec 10, 2001
Posts: 7023
In Java, each case of a switch block must be a constant expression - i.e. each case must be a specific (integral) value. This is not the same as allowing boolean conditions to meet some case, which I'd suspect other languages support.
Now, in your specific situation, depending how closely the actual problem matches the posted example, integral division by 10 might be useful, as would thinking about the default case.

[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
WY Hsiao

Joined: Oct 31, 2003
Posts: 4
Hi all,
There is a program using switch to solve this situation.
Because I am a beginner in java.
If I make a mistake, please tell me and forgive me. ^^
[ code removed -ds ]
Hope this program can do some help!!^^
Please tolerate my poor English
[ October 31, 2003: Message edited by: Dirk Schreckmann ]
Dirk Schreckmann

Joined: Dec 10, 2001
Posts: 7023
Welcome to JavaRanch, WY Hsiao! And thanks for your efforts to help out another Rancher.
I removed the code you'd posted as we prefer to help others learn how to figure out problems 'round these parts.
Hope to see you 'round the Ranch!
I agree. Here's the link:
subject: If-Else to a Switch Statement
jQuery in Action, 3rd edition