pcbf pcbf - 17 days ago 6
Java Question

Can a case in a java switch statement be called more than once?

If I have a java switch statement and I need to call a cases a number of times, is this possible?

So for example:

switch(favouriteIceCream){

case: "vanilla": vanilla();
break;
case: "chocolate": chocolate();
break;
case: "lemon": lemon();
break;
case: "blueberry": blueberry();
}


If I need to call vanilla first, then lemon, then vanilla again and then blueberry twice is there any way of doing this?

Answer

If I need to call vanilla first, then lemon, then vanilla again and then blueberry twice is there any way of doing this?

Switch Case is not to define a flow of handling but to do match a value to a processing. If you have cases to handle several times, extract the switch in a method which takes as parameter the case value and call the method several times with at each time the suitable parameter.

public doProcessing(String str){
  switch (str) {
    case "vanilla": vanilla();
    break;
    case "chocolate": chocolate();
    break;
    case "lemon": lemon();
    break;
    case "blueberry": blueberry();
  }
}

Then call :

doProcessing("vanilla");
doProcessing("lemon");
doProcessing("vanilla");
doProcessing("blueberry");
doProcessing("blueberry");