How to Call Multiple Methods in a Switch Case in Java - java

I'm learning how to build a table in Java with MVC and I am trying to have a switch case that both performs changes to the data in the model and also calls a method like this
public void update()
{ model.fireTableDataChanged(); }
to update the data presented on the table.
Here is the switch case
public Object getValueAt(int row, int col)
{ switch(col)
{ case 0: return row;
case 1: return car.on(car.stops());
default: return ""; }
}
Any assistance is greatly appreciated and if you need to see more of the code to help you answer my question I will provide it.

You seem to be under the incorrect understanding that cases end at the first semicolon. This is incorrect. Cases don't end until you end them with the close brace for the overall switch statement, or until you include a break. Between the case and the end of the case, you can have any number of lines of code that do (pretty much) anything you want.
Think of a switch almost like a function, where the only* way to exit the function is to reach a break statement, return statement, or the close brace at the end, in exactly the same way that you exit functions with return and reaching the end of the function.
switch(condition) {
case 1: fcnOne();
case 2: fcnTwoA(); fcnTwoB();
case 3: fcnThree; break;
default: fcnFour();
}
If the condition is 1 then fcnOne() is called. There is no break in fcnOne(), so the code continues on into case 2. This is often called falling through. fcnTwoA() is then called. The code continues to the next instruction, which is to call fcnTwoB(). The next instruction is fcnThree(). Finally, we encounter a break statement, which exits the switch block.
Yes, I am intentionally ignoring exceptions, System.exit(), and return values for non-void functions.

I've formatted your code differently. Hopefully, it makes it easier to understand the multiple statements. Try something like this:
public Object getValueAt(int row, int col) {
switch(col) {
case 0:
// You can add any number of statements here.
...
update();
return row;
case 1:
...
update();
return car.on(car.stops());
default:
...
update();
return "";
}
}

Related

How to use a switch case in test cases without passing values to switch() method [duplicate]

I've looked at various Q&As on SO similar to this question but haven't found a solution.
What I have is an enum which represents different ways to view a TV Guide...
In the NDroid Application class
static enum guideView {
GUIDE_VIEW_SEVEN_DAY,
GUIDE_VIEW_NOW_SHOWING,
GUIDE_VIEW_ALL_TIMESLOTS
}
...when the user changes the view an event handler receives an int from 0-2 and I'd like to do something like this...
In an Android Activity onClick(DialogInterface dialog, int which) event handler
// 'which' is an int from 0-2
switch (which) {
case NDroid.guideView.GUIDE_VIEW_SEVEN_DAY:
...
break;
}
I'm used to C# enums and select/case statements which would allow something like the above and I know Java does things differently but I just can't make sense of what I need to do.
Am I going to have to resort to if statements? There will likely only ever be 3 choices so I could do it but I wondered how it could be done with switch-case in Java.
EDIT Sorry I didn't completely expand on the issue as I was looking at it as being a generic Java issue. I've added to the question to explain a bit further.
There isn't anything that's Android specific which is why I didn't tag it as Android but the enum is defined in the Application class and the code where I wan't the switch is in an Activity. The enum is static as I need to access it from multiple Activities.
The part you're missing is converting from the integer to the type-safe enum. Java will not do it automatically. There's a couple of ways you can go about this:
Use a list of static final ints rather than a type-safe enum and switch on the int value you receive (this is the pre-Java 5 approach)
Switch on either a specified id value (as described by heneryville) or the ordinal value of the enum values; i.e. guideView.GUIDE_VIEW_SEVEN_DAY.ordinal()
Determine the enum value represented by the int value and then switch on the enum value.
enum GuideView {
SEVEN_DAY,
NOW_SHOWING,
ALL_TIMESLOTS
}
// Working on the assumption that your int value is
// the ordinal value of the items in your enum
public void onClick(DialogInterface dialog, int which) {
// do your own bounds checking
GuideView whichView = GuideView.values()[which];
switch (whichView) {
case SEVEN_DAY:
...
break;
case NOW_SHOWING:
...
break;
}
}
You may find it more helpful / less error prone to write a custom valueOf implementation that takes your integer values as an argument to resolve the appropriate enum value and lets you centralize your bounds checking.
If whichView is an object of the GuideView Enum, following works well. Please note that there is no qualifier for the constant after case.
switch (whichView) {
case SEVEN_DAY:
...
break;
case NOW_SHOWING:
...
break;
}
The enums should not be qualified within the case label like what you have NDroid.guideView.GUIDE_VIEW_SEVEN_DAY, instead you should remove the qualification and use GUIDE_VIEW_SEVEN_DAY
I like a few usages of Java enum:
.name() allows you to fetch the enum name in String.
.ordinal() allow you to get the integer value, 0-based.
You can attach other value parameters with each enum.
and, of course, switch enabled.
enum with value parameters:
enum StateEnum {
UNDEFINED_POLL ( 1 * 1000L, 4 * 1000L),
SUPPORT_POLL ( 1 * 1000L, 5 * 1000L),
FAST_POLL ( 2 * 1000L, 4 * 60 * 1000L),
NO_POLL ( 1 * 1000L, 6 * 1000L);
...
}
switch example:
private void queuePoll(StateEnum se) {
// debug print se.name() if needed
switch (se) {
case UNDEFINED_POLL:
...
break;
case SUPPORT_POLL:
...
break;
This should work in the way that you describe. What error are you getting? If you could pastebin your code that would help.
http://download.oracle.com/javase/tutorial/java/javaOO/enum.html
EDIT: Are you sure you want to define a static enum? That doesn't sound right to me. An enum is much like any other object. If your code compiles and runs but gives incorrect results, this would probably be why.
Short associative function example:
public String getIcon(TipoNotificacao tipo)
{
switch (tipo){
case Comentou : return "fa fa-comments";
case ConviteEnviou : return "icon-envelope";
case ConviteAceitou : return "fa fa-bolt";
default: return "";
}
}
Like #Dhanushka said, omit the qualifier inside "switch" is the key.
enumerations accessing is very simple in switch case
private TYPE currentView;
//declaration of enum
public enum TYPE {
FIRST, SECOND, THIRD
};
//handling in switch case
switch (getCurrentView())
{
case FIRST:
break;
case SECOND:
break;
case THIRD:
break;
}
//getter and setter of the enum
public void setCurrentView(TYPE currentView) {
this.currentView = currentView;
}
public TYPE getCurrentView() {
return currentView;
}
//usage of setting the enum
setCurrentView(TYPE.FIRST);
avoid the accessing of TYPE.FIRST.ordinal() it is not recommended always
I am doing it like
public enum State
{
// Retrieving, // the MediaRetriever is retrieving music //
Stopped, // media player is stopped and not prepared to play
Preparing, // media player is preparing...
Playing, // playback active (media player ready!). (but the media player
// may actually be
// paused in this state if we don't have audio focus. But we
// stay in this state
// so that we know we have to resume playback once we get
// focus back)
Paused; // playback paused (media player ready!)
//public final static State[] vals = State.values();//copy the values(), calling values() clones the array
};
public State getState()
{
return mState;
}
And use in Switch Statement
switch (mService.getState())
{
case Stopped:
case Paused:
playPause.setBackgroundResource(R.drawable.selplay);
break;
case Preparing:
case Playing:
playPause.setBackgroundResource(R.drawable.selpause);
break;
}

Java/C++: possible to have common code for multiple cases in switch?

I find myself running into this situation a lot and was wondering if there are way in Java or C++ or any other language for that matter that allows you to execute code that is common to multiple case statements in a switch but also specialize for individual cases aswell, e.g:
switch(var)
{
case Preceeding:
{
// code executed for both FollowingA and FollowingB
}
break;
case FollowingA:
{
// code executed for only FollowingA
}
break;
case FollowingB:
{
// code executed for only FollowingB
}
break;
}
instead of having to do this:
switch(var)
{
case FollowingA:
case FollowingB:
{
// code executed for FollowingA and FollowingB
switch(var)
{
case FollowingA:
{
// code executed for FollowingA
}
break;
case FollowingB:
{
// code executed for FollowingB
}
break;
}
}
break;
}
It really depends on what you are trying to do - not just from a "can you do this" perspective, but you also have to care for the fact that you or others will have to read and understand the code later.
I typically find that if there are some things that need to be done in more than one case of a switch, it should go into a function (most compilers will inline such code if it's small enough, so there is no performance loss).
So:
void CommonCode()
{
...
}
switch(var)
{
case A:
CommonCode();
...
break;
case B:
CommonCode();
...
break;
}
There are however quite a lot of different solutions to this problem, and it really should follow "what is the meaning of what your code does" that should guide how you solve this. Write code that is clear is the primary goal. If that doesn't work, design the code differently.
}

Java Switch use variable in multiple cases best practice

I want to have a switch statement like the following:
switch (something)
{
case 1:
int a = 3;
...
break;
case 2:
int a = 4;
....
break;
}
This does not work because a can not be redefined in that scope. I see the following options:
just go with "a = 4" in case 2
put each case in braces
define the variable before the switch statement
use a different variable name in case 2
I don't really like any of those four. Which of those is the way to go, or am i missing the best solution?
I saw questions like this one, which suggest using braces, but they are not about the best way to do it, but about getting it to work at all.
I am guessing you are catching any exception with an illegalstateexception and using a default block.
default:
doSomething();
break;
The oracle style guide does not use braces. It also says that a falls through comment should be added wherever a statement has no break.
However, anything with more than one line can be wrapped in braces with no performance penalty, for readability and reliability. The braces tell the compiler to create a new scope and execute that code as a block. If all you do is change a, then it is not really necessary. If you can write your switch case statement on one line without braces, do it. Many things in java don't do braces in one line instances including if statements.
Next, you can redefine any variable you need to re-use or set in the statements outside of the switch statement. This would be the best practice to minimize continual instantiation of your integers.
If there is more then one line,you should try making a few methods then, go with:
int a=0;
switch (something)
{
case 1:{
a = 3;
...
break;
}
case 2:{
a = 4;
....
break;
}
default:
{
try{
throw new IllegalStateException();
}catch(IllegalStateException e)
{
e.printStackTrace();
}
}
}
The braces is the right way to do it. {} creates a new scope, which is exactly what you want.
You can also use Map:
Map<Integer, Integer> caseMap = new HashMap<Integer, Integer>() {{
put(1, 3);
put(2, 4);
}};
int a = caseMap.get(something);

Break in a method called from a loop

I'm refactoring a very large method with a lot of repetition in it.
In the method there are many while loops which include:
if ( count > maxResults){
// Send error response
sendResponse(XMLHelper.buildErrorXMLString("Too many results found, Please refine your search"), out, session);
break;
I want to extract this as a method, because it happens 3 times in this one method currently, but when I do so I get an error on the break as it is no longer within a loop. The problem is that it is still necessary to break out of the while loops, but only when the maximum number of results are reached.
Any suggestions?
Suppose the method is :
public boolean test(int count, int maXResult) {
if ( count > maxResults) {
// Send error response
sendResponse(XMLHelper.buildErrorXMLString("Too many results found, Please refine your search"), out, session);
return true;
}
return false;
}
Call method from loop as :
while(testCondition) {
if (test(count, maxResults)) {
break;
}
}
This is impossible to do directly.
Most often you want to break because you have found the solution and no longer have to search. So indicate in the called function that there is/was success, for instance by returning a result or a boolean to indicate success. And if the function returns success, then break.
If it is now within a method instead of the while loop have it return a value and then break based on that.
i.e.
public bool refactoredMethod(parameters)
{
if ( count > maxResults){
// Send error response
sendResponse(XMLHelper.buildErrorXMLString("Too many results found, Please refine your search"), out, session);
return true;
}
return false;
}
Try to break the loop in the method using return;
As Thriler says you cant do it directly. You could extract part of it to the method and do something like:
if(isTooManyResults(count)) { break; }
Obviously your isTooManyResults method would need to return true if there are too many results and false otherwise

Weird compilation error when using switch on enumeration

I just noticed one curious case and wanted to see if someone will be able to explain it. Here is my case:
private enum Classifiers {
NEURAL_NETWORK, NEAREST_NEIGHBOURS, IDENTITY;
}
private ClassifierInterface getClassifierInstance(Classifiers classifier) {
switch (classifier) {
case NEURAL_NETWORK:
return new DoubleLayeredNeuralNetwork();
case NEAREST_NEIGHBOURS:
return new NearestNeighbours();
case IDENTITY:
return new IdentityClassifier();
}
return null; // If I comment out this line I get compilation error
}
See the comment. I would expect that Unreachable code error will be reported for this line. Instead I get Method must return value error if I comment out this line. However, there is no way the program flow will pass through there.
I even assumed it would be a guard case for the case of null value passed-in, but as expected this triggers NullPointerException for the switch condition.
I do not use switch very often, probably I am missing something here. Can somebody please try to help understand this behaviour?
That is correct behaviour as you do not have a default case statement. The problem is that you could add an value to the enum later and not re-compile the code which uses it. By forcing you to always handle when it is not one of the values, this is covered.
BTW: classifier could be null which is another option switch doesn't handle unfortunately.
That question is interesting...
We have something like this and the compiler is happy!
public enum Coin {
PENNY,
NICKEL,
DIME,
QUARTER;
}
private enum CoinColor { COPPER, NICKEL, SILVER }
private static CoinColor color(Coin c) {
switch(c) {
case PENNY:
return CoinColor.COPPER;
case NICKEL:
return CoinColor.NICKEL;
case DIME: case QUARTER:
return CoinColor.SILVER;
default:
throw new AssertionError("Unknown coin: " + c);
}
}
The Java Languaje Specification says:
A Java compiler is encouraged (but not required) to provide a warning
if a switch on an enum-valued expression lacks a default label and
lacks case labels for one or more of the enum type's constants. (Such
a statement will silently do nothing if the expression evaluates to
one of the missing constants.)

Categories