•
•
•
•
What is DaniWeb IT Discussion Community?
You're currently browsing the Java section within the Software Development category of DaniWeb, a massive community of 456,478 software developers, web developers, Internet marketers, and tech gurus who are all enthusiastic about making contacts, networking, and learning from each other. In fact, there are 2,795 IT professionals currently interacting right now! Registration is free, only takes a minute and lets you enjoy all of the interactive features of the site.
Please support our Java advertiser: Lunarpages Java Web Hosting
Views: 4153 | Replies: 1
![]() |
•
•
•
•
Hi, I am new to java. i want to use a switch statement on operators that are in read as strings. Like "==","!=",">=","<=".
Please help me to do this as i cannot use even their ascii value of these operators to switch the cases.
Switch statements can only be used on ints or enums. For strings you are stuck with if-else-if blocks or stucturing your code in such as way as to use subclasses to provide the behavior instead of a switch.
That said, if you really want a switch, you can provide a string switching capability with an enum if you code it right. Here's an example just for giggles
import java.util.HashMap;
import java.util.Map;
public enum Operator {
EQUALS("=="),
NOT_EQUALS("!="),
GREATER_EQUALS(">="),
LESS_EQUALS("<=");
private final String token;
private static Map<String,Operator> tokenMap;
private Operator(String token){
this.token = token;
map(token,this);
}
private static void map(String token, Operator op){
if (tokenMap==null) tokenMap = new HashMap<String,Operator>();
tokenMap.put(token,op);
}
public static Operator forToken(String token){
return tokenMap.get(token);
}
public static void main(String[] args) {
String[] operators = new String[]{"<=","==","!=",">="};
for (String opString : operators){
Operator op = Operator.forToken(opString);
switch (op) {
case EQUALS:
System.out.println("equals");
break;
case NOT_EQUALS:
System.out.println("not equals");
break;
case GREATER_EQUALS:
System.out.println("greater than or equal to");
break;
case LESS_EQUALS:
System.out.println("less than or equal to");
break;
}
}
}
}For your case though, you may as well just use an if-else block.
![]() |
•
•
•
•
•
•
•
•
DaniWeb Java Marketplace
•
•
•
•
Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
- C# beginner switch statement (C#)
- switch statement on String in Java (Java)
- switch statement (C)
- Switch Statement, Fall-Through. (C)
- Problems with switch statement (C++)
- Problems with switch statement (C++)
Other Threads in the Java Forum
- Previous Thread: Logic Error? (Need Help, Getting Exception Part II lol)
- Next Thread: is it possible to link a java file?



Linear Mode