I am trying to explore substrings using switch case block. for now I am trying to do this:
switch(splitedString[0]){
case(.contains("int")):
}
When I need to create new object when the case is met. There is any option to activate method on the switch argument?
You can not do such thing. Also putting string in a switch statement is more like if statement.
Instead of using switch use if's
sample:
if(splitedString[0].contains("int"))
Related
I have two switch statements that are identical in structure but the cases do different things. How do I possibly combine them? Or are there any better design suggestions instead of using two switch statements?
This is how the first switch statement looks:
switch(var){
case 1:
functionA();
break;
case 2:
functionB();
break;
}
The second looks like this:
switch(var){
case 1:
functionC();
break;
case 2:
functionD();
break;
}
Problem is, functionA() cannot be called at the same time with functionC() and same goes for functionB() and functionD() - they are to be called at different times.
Forgive me if this sounds silly, but is there a way to re-use one switch statement for different situations?
NB: This is not a "how do I do this?" question, but a "how do I do this BETTER question".
In my optionion there is no need to further simplify your switch statements, since they are readable and do different things. Also, in order to simplify you would need to add an additional layer of abstraction, which is not (really) possible here.
The only thing you could abstract here is the var parameter. Altough i would not recommend it, maybe you can try something like this:
private Consumer<Integer> createConsumer(Runnable... actions) {
return i -> {
if (actions.length < i)
throw new IllegalArgumentException();
actions[i].run();
};
}
You can create a consumer, which accepts an arbitary amount of Runnable objects
var consumer = createConsumer(
() -> System.out.println("First"),
() -> System.out.println("Second"),
() -> System.out.println("Third"));
and execute it like
consumer.accept(0);
If you also need a default statement Consumer<Integer> createConsumer(Runnable... actions, Runnable defaultOption) could come to rescue, then the IllegalArgumentException would also be superfluous.
However, this would just be some functional style of switch statement, which could make things even more complicated, whenever the parameter does not start at 0, but some other number (you would need to subtract till 0) or if you switch block has "gaps" bewteen numbers (0, 1, 3, ...).
Is there an option in the Eclipse workspace properties to change the order that the "incomplete-switch" warning auto-populates cases within the switch statement? For example, if I have an enum:
enum TraversalType{
PREORDER,
INORDER,
POSTORDER;
}
When you use this and have the switch statement warning auto complete the cases within the body of the switch, it seems to always order alphabetically. Is there an option to change this and use the ordering, like in this example, to look like:
switch(TraversalType pType){
case PREORDER:
break;
case INORDER:
break;
case POSTORDER:
break;
}
every time, instead of just after manually entering the cases?
You can't change the ordering of case statements in the Eclipse auto complete feature of "add missing case statements". However you can sort the enum members alphabetically to match the order of the auto inserted switch cases.
I am attempting to create it so the user will type in a keyword and it will execute that case. This works fine, but I would like the user to also be able to write after the keyword and it will still find the correct case. For example, the user might input "SEARCH dogs and cats" and it would run the "SEARCH" case.
I attempted to do have a temporary variable that stored only the "SEARCH" portion of the string, but I received an error that it had to be a constant in the switch statements. Is there a workaround or will I have to use if else statements?
Here is some test code with the error:
switch(textField.getText)
{
case SEARCH: case textField.getText().split(" ", 2)[0]: // Error is occuring on the second case statement
// Statements
break;
case Default:
lblOutput.setText("ERROR: NOT FOUND");
}
You need to specify one of three things in a case statement:
A constant
An Enum
Default keyword
Refer to
https://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.11
In addition, you have a "case" within a "case" with no intermediate "switch" statement.
I have a problem concerning switch/case statements in java in combination with enums.
In my code I want to do something based on the Enum of the type "MatchingMethods" set in the object "currentMethod".
The enum "MatchingMethods" contains several enums in the form
{EXACT_STRING_MATCHING, DEPTH_MATCHING, [...]}
Now the strange thing is though the object "currentMethod" contains an enum of the type "EXACT_STRING_MATCHING" not only the first case is executed but also the second one.
I know there is no break statement after the code of the first case but the code of the second case shouldn't be executed in my opinion because the enum "EXACT_STRING_MATCHING" doesn'T match with "DEPTH_MATCHING".
If I put in a break statement after the first case it seem to be totally fine…
My code is the following:
[...]
MatchingMethods mM = currentMethod.getMatchMethod();
switch (currentMethod.getMatchMethod()) {
case EXACT_STRING_MATCHING:
//do something here
case DEPTH_MATCHING:
comparedNodePair.setDepthMatchResult(currentMetricResult);
break;
[...]
I am totally confused…
May someone be able to help me?
You already mentioned it, you have no break - switch works like goto where the case are labels to be jumped at and no "boundaries" or functions.
This is also the biggest critique concerning switch, because no one would use goto today, but switch which is certainly similar.
But it gets executed, because once one of the case satements is true the flow of execution "falls trough" see here for some information
this is normal if there is no break statement at the end of the case block.
add the break statement is necessary if you only want the exact block to be executed.
For example:
3 methods exist
"map1method,
map2method,
map3mehtod"
and I want to call the right one depending on what the integer 'activemap' has currently stored in it.
I could do an If statement
"If (activemap == 1)
map1method;
elseif (activemap ==2)
..."
But is there a possible way of using the integer more efficiently?
Like a "map(activemap)method"
Also could I also call a specific array in a batch of them in the same fashion.
This is all in java by the way.
It is possible via reflection but I would urge you to stay away from that approach. Why not have all three methods built into one? One option would be to use a switch statement to handle the various cases:
void mapMethod(int activemap) {
switch (activemap) {
case 1:
// map1method
break;
case 2:
// map2method
break;
case 3:
// map3method
break;
default:
break;
}
}
Now, you can call
mapMethod(activemap)
If you want to take the reflection approach instead (which as I said I don't think you should), you can do something along the lines of
String methodName = "map" + activemap + "method";
MyClass.class.getDeclaredMethod(methodName).invoke(null);
A switch statement would be slightly easier to read:
switch(activemap) {
case 1: map1method(); break;
case 2: map2method(); break;
}
You could use reflection to build the method name up at runtime, but that wouldn't be simpler. Reflection is a lot of code.
The most effective way to do this is to either create an enum to represent the different calls and use the int as a lookup for the enum value, or if that's not possible, to use a switch statement. You can use reflection to accomplish what you're talking about (look up a method at runtime based on its name), but it's less efficient and more cumbersome than either of those options.
You can do it using Reflection, It will be something like this:
java.lang.reflect.Method method;
method = myObject.getClass().getMethod("map+"activemap"+method", param1.class, param2.class, ..);
method.invoke(object, arg1, arg2,...);