How to make a sleep thread in For loop? - java

I'm working on a card game app and i finished the basic stuff and now i'm trying to make it look professional.
the first thing I want to do is the effect of the distribution of cards,
i want to make a shuffle card effect.
when a card is given to a player, I want at least 500 milliseconds difference to the next card that will be distributed to him.
ideas?
this is a part from my code..
private void SetTheGame() {
SetShuffleSound();
for ( int i = 0; i < Imagename.length;i++) {
Imagename[i] = (ImageView) findViewById(WTF[i]);
CountCards();
Random = getRandom();
SwitchImages SwitchMe = new SwitchImages(myNewArray[Random]);
int first = SwitchMe.ChangeImages();
Imagename[i].setImageResource(myNewArray[Random]);
Imagename[i].setVisibility(View.VISIBLE);
CardsCount valueOfCard = new CardsCount(myNewArray[Random]);
int a = valueOfCard.WhatsMyValue();
String b = valueOfCard.TheFamily();
switch (i) {
case 0:
if (first != 0) {
Imagename[0].setImageResource(first);
}
FirstColumnComputer.add(a);
FirstColumnComputerFAMILY.add(b);
break;
case 1:
if (first != 0) {
Imagename[1].setImageResource(first);
}
SecondColumnComputer.add(a);
SecondColumnComputerFAMILY.add(b);
break;
case 2:
if (first != 0) {
Imagename[2].setImageResource(first);
}
ThirdColumnComputer.add(a);
ThirdColumnComputerFAMILY.add(b);
break;
case 3:
if (first != 0) {
Imagename[3].setImageResource(first);
}
FourColumnComputer.add(a);
FourColumnComputerFAMILY.add(b);
break;
case 4:
if (first != 0) {
Imagename[4].setImageResource(first);
}
FifthColumnComputer.add(a);
FifthColumnComputerFAMILY.add(b);
break;
case 5:
FirstColumnPlayer.add(a);
FirstColumnPlayerFAMILY.add(b);
break;
case 6:
SecondColumnPlayer.add(a);
SecondColumnPlayerFAMILY.add(b);
break;
case 7:
ThirdColumnPlayer.add(a);
ThirdColumnPlayerFAMILY.add(b);
break;
case 8:
FourColumnPlayer.add(a);
FourColumnPlayerFAMILY.add(b);
break;
case 9:
FifthColumnPlayer.add(a);
FifthColumnPlayerFAMILY.add(b);
break;
}
Cards.remove(Random);
// MakeTheCardPause();
}
SentTheLinkedList();
}
MakeTheCardPause() is the problem...
private void MakeTheCardPause() {
Thread Timer = new Thread()
{
public void run()
{
try{
sleep(1000);
}catch(InterruptedException e)
{
e.printStackTrace();
}finally
{
//do something...
}
}
};
Timer.start();
}
thanks!

Many ways you can do this. Thread.sleep(500) is the way was you suggested but it is not what I would recommend. Here are two alternatives
Message Handler
An example
Handler mHandler = new Handler(){
public void handleMessage(Message msg){
super.handleMessage(msg);
switch(msg.what){
case shuffle:
// Do something
break;
case doneShuffle:
//Do something
}
}
};
Asynch Tasks
Here is an example:
private class shuffleCards extends AsyncTask<Card, Integer, Long> {
protected Long doInBackground(Card card) {
//Do something
//shuffle deck
// Escape early if cancel() is called
if (isCancelled()) break;
}
return deck;
}
protected void onProgressUpdate(Integer... progress) {
//Number of shuffled cards??
}
protected void onPostExecute(Long result) {
//Show card
}
}
Remember this is just a background task to display results. Your main thread will be handling the actual card values and handing them over to the Asynch task.
Good Luck

What about this? You need to have the sleep in the working thread, your code above is creating a new thread and telling it to sleep, which has no noticeable effect to the user.
private void SetTheGame() {
SetShuffleSound();
for ( int i = 0; i < Imagename.length;i++) {
Imagename[i] = (ImageView) findViewById(WTF[i]);
CountCards();
Random = getRandom();
SwitchImages SwitchMe = new SwitchImages(myNewArray[Random]);
int first = SwitchMe.ChangeImages();
Imagename[i].setImageResource(myNewArray[Random]);
Imagename[i].setVisibility(View.VISIBLE);
CardsCount valueOfCard = new CardsCount(myNewArray[Random]);
int a = valueOfCard.WhatsMyValue();
String b = valueOfCard.TheFamily();
switch (i) {
case 0:
if (first != 0) {
Imagename[0].setImageResource(first);
}
FirstColumnComputer.add(a);
FirstColumnComputerFAMILY.add(b);
break;
case 1:
if (first != 0) {
Imagename[1].setImageResource(first);
}
SecondColumnComputer.add(a);
SecondColumnComputerFAMILY.add(b);
break;
case 2:
if (first != 0) {
Imagename[2].setImageResource(first);
}
ThirdColumnComputer.add(a);
ThirdColumnComputerFAMILY.add(b);
break;
case 3:
if (first != 0) {
Imagename[3].setImageResource(first);
}
FourColumnComputer.add(a);
FourColumnComputerFAMILY.add(b);
break;
case 4:
if (first != 0) {
Imagename[4].setImageResource(first);
}
FifthColumnComputer.add(a);
FifthColumnComputerFAMILY.add(b);
break;
case 5:
FirstColumnPlayer.add(a);
FirstColumnPlayerFAMILY.add(b);
break;
case 6:
SecondColumnPlayer.add(a);
SecondColumnPlayerFAMILY.add(b);
break;
case 7:
ThirdColumnPlayer.add(a);
ThirdColumnPlayerFAMILY.add(b);
break;
case 8:
FourColumnPlayer.add(a);
FourColumnPlayerFAMILY.add(b);
break;
case 9:
FifthColumnPlayer.add(a);
FifthColumnPlayerFAMILY.add(b);
break;
}
Cards.remove(Random);
long sleepMax = 1000L;
Random r = new Random();
long delay = (long) (r.nextDouble() * range);
Thread.sleep(delay);
}
SentTheLinkedList();
}

Related

Java Switch between cases without every time skipping the remaining cases

I am new to Java, would appreciate some help.
what I am trying to do here is switch between the cases. However what I also need is to not skip the remaining cases in this procedure.
I mean the code below should output:
two
four
three
four
public class X {
public static void main(String[] args) {
String n = "two";
while(true)
{
switch (n)
{
case "zero":
{
System.out.println("zero");
n="one";
}
case "one":
{
System.out.println("one");
n="three";
}
case "two":
{
System.out.println("two");
if (12>3)
{
n="four";
break;
}
}
case "three":
{
System.out.println("three");
}
case "four":
{
System.out.println("four");
return;
}
}
}
}
}
I have used return to end the while loop. Now I do understand that I have used break in case two which will break the current switch and thereby not complete it. But if i don't, I just can't switch between cases in the first place. So, I need a different solution. And working implementation in java should be helpful. Thanks
You can use Queue for this.
Each case is responsible to add the next one to the queue by the order of expected execution.
Queue q = new LinkedList();
q.add("two");
String n = (String)q.poll();
while(n!=null)
{
switch (n)
{
case "zero":
{
System.out.println("zero");
q.add("one");
break;
}
case "one":
{
System.out.println("one");
q.add("three");
q.add("two");
break;
}
case "two":
{
System.out.println("two");
if (12>3)
{
q.add("four");
}
q.add("three");
break;
}
case "three":
{
System.out.println("three");
q.add("four");
break;
}
case "four":
{
System.out.println("four");
break;
}
}
n=(String) q.poll();
}
The problem does not lie within the switch statement. You simply need to distinguish from where you 'came from'.
To do that you need to remember it, e.g. in a local variable:
String lastN;
and in the loop before the switch:
lastN = n;
Now you can do something like:
case "four":
{
System.out.println("four");
if("three".equals(lastN))
{
return;
}
else
{
n = "three";
break;
}
}
Your code is working as it should, if what you need is a fall through
then consider the fact that case zero and one must be executed first...
on the other hand, you don't need to add { } to the case group
case "zero": {
System.out.println("zero");
n = "one";
}
public static void main(String[] args) {
String n = "two";
while(true)
{
switch (n)
{
case "zero":
{
System.out.println("zero");
}
case "one":
{
System.out.println("one");
}
case "two":
{
System.out.println("two");
}
case "four":
{
System.out.println("four");
if(n=="four"){
return;
}
}
case "three":
{
System.out.println("three");
n="four";
}
}
}
}

Java - Guava Table Not Returning Value

I am using Google's Guava library for the Table class.
I have the table define like this:
private Table<ThreePartKey, DateTime, UnitDay> table = TreeBasedTable.create();
ThreePartKey is an object that contains 3 string values as fields. It is being used as the Row index in the table. DateTime is a Joda Time object being used as the Column index of the table. UnitDay is a plain old java object that is the Value of the table.
I have populated the table, and later in my code I want to access a specific cell of the table. I use the following code:
UnitDay tempUnitDay = table.get(threePartKey, dateTime);
But tempUnitDay is null. I've run this in Eclipse debug mode, and neither threePartKey nor dateTime is null. There should not be a null value in the table.
Does anyone have any idea what I am doing wrong?
EDIT:
#TR1 I thought of that, but it should have a value for that column/row. I created a list of ThreePartKeys and a list of DateTimes, then created a table from those lists with an empty UnitDay as the value. Then I go back an iterate through the same values again to populate the UnitDay values.
Here is the code for my ThreePartKey class:
public class ThreePartKey implements Comparable<ThreePartKey> {
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((facilityCode == null) ? 0 : facilityCode.hashCode());
result = prime
* result
+ ((facilityGroupCode == null) ? 0 : facilityGroupCode
.hashCode());
result = prime * result
+ ((unitCode == null) ? 0 : unitCode.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ThreePartKey other = (ThreePartKey) obj;
if (facilityCode == null) {
if (other.facilityCode != null)
return false;
} else if (!facilityCode.equals(other.facilityCode))
return false;
if (facilityGroupCode == null) {
if (other.facilityGroupCode != null)
return false;
} else if (!facilityGroupCode.equals(other.facilityGroupCode))
return false;
if (unitCode == null) {
if (other.unitCode != null)
return false;
} else if (!unitCode.equals(other.unitCode))
return false;
return true;
}
private String facilityGroupCode;
private String facilityCode;
private String unitCode;
public void setFacilityGroupCode (String facilityGroupCode) {
this.facilityGroupCode = facilityGroupCode;
}
public void setFacilityCode (String facilityCode) {
this.facilityCode = facilityCode;
}
public void setUnitCode (String unitCode) {
this.unitCode = unitCode;
}
public String getFacilityGroupCode () {
return facilityGroupCode;
}
public String getFacilityCode () {
return facilityCode;
}
public String getUnitCode () {
return unitCode;
}
#Override
public int compareTo(ThreePartKey o) {
return (100*(unitCode.compareTo(o.unitCode))) +
(10*(facilityCode.compareTo(o.unitCode))) +
(facilityGroupCode.compareTo(o.facilityGroupCode));
}
}
And here is my code that creates the table:
public void setUpTable () {
for (DateTime day : uniqueDays) {
for (ThreePartKey unit : trueUniqueUnits) {
UnitDay unitDay = new UnitDay();
String unitCode = unit.getUnitCode();
unitDay.setDay(day);
unitDay.setUnitCode(unit.getUnitCode());
unitDay.setFacilityCode(unit.getFacilityCode());
unitDay.setFacilityGroupCode(unit.getFacilityGroupCode());
table.put(unit, day, unitDay);
}
}
}
public void populateTable () { //FIX THIS TO INCLUDE ThreePartKey
for (CensusHour hour : allHours) {
DateTime minHour = hour.getDateTaken().withTimeAtStartOfDay();
DateTime day = hour.getDateTaken().withTimeAtStartOfDay();
String unit = hour.getUnitCode();
ThreePartKey key = new ThreePartKey();
key.setFacilityCode(hour.getFacilityCode());
key.setFacilityGroupCode(hour.getFacilityGroupCode());
key.setUnitCode(hour.getUnitCode());
UnitDay tempUnitDay = table.get(key, day);
tempUnitDay.setFacilityId(hour.getFacilityId());
tempUnitDay.setFacilityName(hour.getFacilityName());
tempUnitDay.setUnitId(hour.getUnitId());
tempUnitDay.setUnitName(hour.getUnitName());
tempUnitDay.setPortalCensusFileId(hour.getPortalCensusFileId());
tempUnitDay.setDay(minHour);
tempUnitDay.setFacilityCode(hour.getFacilityCode());
tempUnitDay.setFacilityGroupCode(hour.getFacilityGroupCode());
tempUnitDay.setFacilityGroupName(hour.getFacilityGroupName());
int objectHour = hour.getHourOfDay();
double occupancy = hour.getOccupancy();
switch (objectHour) {
case 0: tempUnitDay.setCensusHour0(occupancy);
break;
case 1: tempUnitDay.setCensusHour1(occupancy);
break;
case 2: tempUnitDay.setCensusHour2(occupancy);
break;
case 3: tempUnitDay.setCensusHour3(occupancy);
break;
case 4: tempUnitDay.setCensusHour4(occupancy);
break;
case 5: tempUnitDay.setCensusHour5(occupancy);
break;
case 6: tempUnitDay.setCensusHour6(occupancy);
break;
case 7: tempUnitDay.setCensusHour7(occupancy);
break;
case 8: tempUnitDay.setCensusHour8(occupancy);
break;
case 9: tempUnitDay.setCensusHour9(occupancy);
break;
case 10: tempUnitDay.setCensusHour10(occupancy);
break;
case 11: tempUnitDay.setCensusHour11(occupancy);
break;
case 12: tempUnitDay.setCensusHour12(occupancy);
break;
case 13: tempUnitDay.setCensusHour13(occupancy);
break;
case 14: tempUnitDay.setCensusHour14(occupancy);
break;
case 15: tempUnitDay.setCensusHour15(occupancy);
break;
case 16: tempUnitDay.setCensusHour16(occupancy);
break;
case 17: tempUnitDay.setCensusHour17(occupancy);
break;
case 18: tempUnitDay.setCensusHour18(occupancy);
break;
case 19: tempUnitDay.setCensusHour19(occupancy);
break;
case 20: tempUnitDay.setCensusHour20(occupancy);
break;
case 21: tempUnitDay.setCensusHour21(occupancy);
break;
case 22: tempUnitDay.setCensusHour22(occupancy);
break;
case 23: tempUnitDay.setCensusHour23(occupancy);
break;
}
table.put(key, day, tempUnitDay);
}
}

Reviewing and correcting code style [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am new to android developement.
Created calculator application.
Want to improve my code quality.
Will be helpfull for any advice to make the code better and more professional
(overall structure, splitting onto logical units, accordance to code conventions, methods and variables names, comments etc).
Here is my code:
public class OperationsAndFunctions {
static enum OperEnum {
SUM, SUBSTRACT, MULTIPLY, DIVIDE, EQUAL
}
static enum FuncEnum {
RESET, BACKSPACE, SIGN, PERCENT, POINT
}
}
public class LCalculator extends Activity {
private TextView mDisplay;
private boolean mDisplayIsEmpty = true;
private boolean mFirstNumberReceived;
private boolean mNumberEntered;
private boolean mPointEntered;
private double sNum1;
private double sNum2;
private static OperationsAndFunctions.OperEnum sOperation;
private static OperationsAndFunctions.FuncEnum sFunction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
mDisplay = (TextView) findViewById(R.id.tvDisplay);
mDisplay.setText("0");
}
// listening for number buttons pressing
public void num_Clicked(View view) {
Button button = (Button) view;
int number = 0;
// checking button ID
switch (button.getId()) {
case R.id.button1:
number = 1;
break;
case R.id.button2:
number = 2;
break;
case R.id.button3:
number = 3;
break;
case R.id.button4:
number = 4;
break;
case R.id.button5:
number = 5;
break;
case R.id.button6:
number = 6;
break;
case R.id.button7:
number = 7;
break;
case R.id.button8:
number = 8;
break;
case R.id.button9:
number = 9;
break;
case R.id.button0:
if (mDisplay.getText().toString().equals("0")) {
return;
}
number = 0;
break;
}
// setting a new digit onto display if it is empty
if (mDisplayIsEmpty) {
if (!(number == 0)) {
mDisplayIsEmpty = false;
}
mDisplay.setText(Integer.toString(number));
}
// appending digit if display isn't empty
else {
mDisplay.append(Integer.toString(number));
}
mNumberEntered = true;
}
// listenning for operational buttons pressing
public void op_Clicked(View view) {
Button button = (Button) view;
// calculating and printing result
// if a number has been entered before
// (Not entering here if another operation has been pressed before)
if (mNumberEntered) {
// if received first number and saved to sNum1
if (mFirstNumberReceived) {
sNum2 = Double.parseDouble(mDisplay.getText().toString());
printResult(calculateResult(sNum1, sOperation, sNum2));
sNum1 = Double.parseDouble(mDisplay.getText().toString());
}
// if not received first number - receiving it now
else {
sNum1 = Double.parseDouble(mDisplay.getText().toString());
mFirstNumberReceived = true;
}
mNumberEntered = false;
}
// checking operational buttons id
// and assigning appropriate operations enum value
switch (button.getId()) {
case R.id.buttonPlus:
sOperation = OperationsAndFunctions.OperEnum.SUM;
break;
case R.id.buttonMinus:
sOperation = OperationsAndFunctions.OperEnum.SUBSTRACT;
break;
case R.id.buttonMultiply:
sOperation = OperationsAndFunctions.OperEnum.MULTIPLY;
break;
case R.id.buttonDivide:
sOperation = OperationsAndFunctions.OperEnum.DIVIDE;
break;
case R.id.buttonEqual:
sOperation = OperationsAndFunctions.OperEnum.EQUAL;
break;
}
// next digit entered will be a new number
mDisplayIsEmpty = true;
mPointEntered = false;
}
// listening for functional buttons pressing
public void func_Clicked(View view) {
Button button = (Button) view;
// checking operational buttons id
// and assigning appropriate functions enum value
switch (button.getId()) {
case R.id.buttonAc:
sFunction = OperationsAndFunctions.FuncEnum.RESET;
break;
case R.id.buttonC:
sFunction = OperationsAndFunctions.FuncEnum.BACKSPACE;
break;
case R.id.buttonSign:
sFunction = OperationsAndFunctions.FuncEnum.SIGN;
break;
case R.id.buttonPercent:
sFunction = OperationsAndFunctions.FuncEnum.PERCENT;
break;
case R.id.buttonPoint:
sFunction = OperationsAndFunctions.FuncEnum.POINT;
break;
}
// implementing chosen function
implementFunction(sFunction);
}
// implementing function
private void implementFunction(OperationsAndFunctions.FuncEnum function) {
sFunction = function;
switch (function) {
case RESET:
reset();
break;
case BACKSPACE:
printResult(Double.parseDouble(backSpace(mDisplay.getText())
.toString()));
break;
case SIGN:
printResult(readDisplayState() * (-1));
break;
case PERCENT:
printResult(readDisplayState() / 100);
break;
case POINT:
if (!mPointEntered) {
if (!mDisplayIsEmpty) {
mDisplay.append(".");
} else {
mDisplay.setText("0.");
mDisplayIsEmpty = false;
}
mPointEntered = true;
}
break;
}
}
// reseting the calculator
private void reset() {
mDisplay.setText("0");
sNum1 = sNum2 = 0;
mDisplayIsEmpty = true;
mFirstNumberReceived = false;
mNumberEntered = false;
mPointEntered = false;
}
// deleting the last symbol on display
private CharSequence backSpace(CharSequence displayState) {
CharSequence result = displayState;
if (displayState.length() > 1) {
result = displayState.subSequence(0, displayState.length() - 1);
}
else if (displayState.length() == 1) {
result = "0";
}
return result;
}
// calculating the result
private double calculateResult(double num1,
OperationsAndFunctions.OperEnum operation, double num2) {
sNum1 = num1;
sNum2 = num2;
sOperation = operation;
double result = 0;
switch (operation) {
case SUM:
result = num1 + num2;
break;
case SUBSTRACT:
result = num1 - num2;
break;
case MULTIPLY:
result = num1 * num2;
break;
case EQUAL:
mDisplayIsEmpty = true;
mNumberEntered = false;
mFirstNumberReceived = false;
break;
case DIVIDE:
// division by zero
if (num2 == 0) {
showError();
break;
}
result = num1 / num2;
break;
}
return result;
}
// reading current displayNumber
private double readDisplayState() {
return Double.parseDouble(mDisplay.getText().toString());
}
// printing the result
private void printResult(Double result) {
// checking if the result having decimal part
// if not then we print integer value of it without point and zero(s)
if (result % 1 == 0) {
mDisplay.setText(Integer.toString(result.intValue()));
}
else {
mDisplay.setText(Double.toString(result));
}
}
// Error message (in case of division by zero)
private void showError() {
// printing error message
mDisplay.setText("Error");
// and reseting current state
sNum1 = sNum2 = 0;
mDisplayIsEmpty = true;
mFirstNumberReceived = false;
mNumberEntered = false;
mPointEntered = false;
}
}
Thank you very much in advance!
Code style can be either a personal preference, or an organizational guideline. If working for yourself, do what works best for you. Start with some published standard code guidelines (Android Style Guide) and then change things that you don’t like. If you are working within a group, be it an open source project or as part of a project with an employer, there are typically coding standards set forth by them. One bit of advice is even if you are not a fan of the chosen style, abide by it. Having an entire file show as updated just because you reformatted the style to match your preferences is not received well in a team environment. As far as code quality, there are tools (Static analysis) that you can run against your code to give you suggestions of what might be places that could cause problems. (Android Static Analysis)

How to make a switch statement loop back to beginning

I have a JButton called nextAd that increments my private int i; plus 1 each time it is clicked, which shows different images on each click. After the button is clicked a fourth time, I want my GUI to loop back to when the button was clicked 0 times, showing what was initially on the screen when I first ran the program.
Question: How can I make my switch statement loop back to what was initially on my screen when I first launch my GUI program?
I've omitted the rest of my code except for the button clicked action. If more code is required in order to answer the question, please let me know.
private class buttonListener implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
{
if(e.getSource() == nextAd)
{
i++;
}
switch (i){
case 1:
appleTitle.setVisible(false);
appleAdPic.setVisible(false);
appleLogo.setVisible(false);
IBMTitle.setVisible(true);
IBMAdPic.setVisible(true);
IBMLogo.setVisible(true);
break;
case 2:
IBMTitle.setVisible(false);
IBMAdPic.setVisible(false);
IBMLogo.setVisible(false);
microsoftTitle.setVisible(true);
microsoftAdPic.setVisible(true);
microsoftLogo.setVisible(true);
break;
case 3:
microsoftTitle.setVisible(false);
microsoftAdPic.setVisible(false);
microsoftLogo.setVisible(false);
samsungTitle.setVisible(true);
samsungAdPic.setVisible(true);
samsungLogo.setVisible(true);
break;
}
}
}
}
}
I think the easiest solution would be just to set the increment value to 0 at the end of actionPerformed() if i == 3;
public void actionPerformed(ActionEvent event) {
// ...
if (i == 3) {
i = 0; // Reset the ad counter to 0, to restart the ad loop
}
}
That way, the next time actionPerformed() is called, it will start at the beginning.
You could change the start of your event handler to:
if(e.getSource() == nextAd)
{
i = (i == 3 ? 1 : i + 1);
}
Can we not have a default case and inside you can set the so-called 0-times scenario ?
For e.g.:
default:
appleTitle.setVisible(false);
appleAdPic.setVisible(false);
appleLogo.setVisible(false);
IBMTitle.setVisible(false);
IBMAdPic.setVisible(false);
IBMLogo.setVisible(false);
break;
Probably the best way to do it would be to put the switch statement into a seperate method of return type void, much like
private class buttonListener implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
{
if(e.getSource() == nextAd)
{
i++;
}
switching()
}
}
}
public static void switching() {
switch (i){
case 1:
appleTitle.setVisible(false);
appleAdPic.setVisible(false);
appleLogo.setVisible(false);
IBMTitle.setVisible(true);
IBMAdPic.setVisible(true);
IBMLogo.setVisible(true);
break;
case 2:
IBMTitle.setVisible(false);
IBMAdPic.setVisible(false);
IBMLogo.setVisible(false);
microsoftTitle.setVisible(true);
microsoftAdPic.setVisible(true);
microsoftLogo.setVisible(true);
break;
case 3:
microsoftTitle.setVisible(false);
microsoftAdPic.setVisible(false);
microsoftLogo.setVisible(false);
samsungTitle.setVisible(true);
samsungAdPic.setVisible(true);
samsungLogo.setVisible(true);
break;
}
case 4:
i = 0;
switching();
break;
}
Here is what I would do :
if (e.getSource() == nextAd) {
if (i >= 3) {
i = 1;
} else {
i++;
}
}
Here was my solution.
Thanks everyone!
if(e.getSource() == nextAd)
{
i++;
{
if(i == 5)
{
i = 0;
samsungTitle.setVisible(false);
samsungAdPic.setVisible(false);
samsungLogo.setVisible(false);
}
switch (i){
case 1:
appleTitle.setVisible(true);
appleAdPic.setVisible(true);
appleLogo.setVisible(true);
break;
case 2:
appleTitle.setVisible(false);
appleAdPic.setVisible(false);
appleLogo.setVisible(false);
IBMTitle.setVisible(true);
IBMAdPic.setVisible(true);
IBMLogo.setVisible(true);
break;
case 3:
IBMTitle.setVisible(false);
IBMAdPic.setVisible(false);
IBMLogo.setVisible(false);
microsoftTitle.setVisible(true);
microsoftAdPic.setVisible(true);
microsoftLogo.setVisible(true);
break;
case 4:
microsoftTitle.setVisible(false);
microsoftAdPic.setVisible(false);
microsoftLogo.setVisible(false);
samsungTitle.setVisible(true);
samsungAdPic.setVisible(true);
samsungLogo.setVisible(true);
break;
}
}
}
}
}
}
}

Alternative to Nested Switch Statements in Java

So I wrote a method today that incorporated the use of nested switch statements, and the code looked fairly clean and concise to me, but I was told that nested switch statements are not typically the best way to go as they can get confusing with the more switch statements that you add on. Here is a sample of what my code looked like:
EnumOne enumOne;
EnumTwo enumTwo = null;
EnumTwo enumThree = null;
switch (enumOne) {
case CASE_ONE:
switch (enumTwo){
case A: enumTwo = EnumTwo.B; break;
case C: enumTwo = EnumTwo.D; break;
default: break;
}
switch (enumThree) {
case AA: enumThree = EnumTwo.BB; break;
case CC: enumThree = EnumTwo.DD; break;
default: break;
}
break;
case CASE_TWO:
case CASE_THREE:
switch(EnumTwo) {
default: break;
}
switch (enumThree) {
case AA: enumThree = EnumTwo.XX; break;
case CC: enumThree = EnumTwo.YY; break;
default: break;
}
break;
default:
break;
}
So my question would be, essentially, what would be a suitable alternative to these switch statements?
As using a lot of switch becomes pretty hard to read.
And any time a new case arises then we have to modify code and add a CASE
we can consider using polymorphism in such cases
I am going to give a simple class just to let you understand.
Suppose a class earlier with switch case
class Test
{
Animal a;
public Test(Animal a)
{
this.a=a;
}
public moveThisAnimal()
{
switch(this.a)
{
case fish:
System.out.println("swim");
break;
case dog:
System.out.println("walk");
break;
case bird:
System.out.println("fly");
break;
}
}
}
now we replace these switch with our polymorphism logic
Interface Animal
{
String move();
}
Class Dog implements Animal
{
public String move()
{
return "walk";
}
}
Class Bird implements Animal
{
public String move()
{
return "fly";
}
}
Class Fish implements Animal
{
public String move()
{
return "swim";
}
}
now we have Test class without switch case
class Test
{
Animal a;
public Test(Animal a)
{
this.a=a;
}
public moveThisAnimal()
{
System.out.println(this.a.move()); // all switch case statements removed
}
}
and even if we have to add further cases we have to just add implementations no change here
See your complete code and see if It is possible to Do
I recommend you replace each nested switch statement with a call to a procedure which then executes the nested switch code.
Write something like this instead:
EnumOne enumOne;
EnumTwo enumTwo = null;
EnumTwo enumThree = null;
switch (enumOne)
{
case CASE_ONE:
nested_switch1();
case CASE_TWO:
case CASE_THREE:
nested_switch2();
break;
default:
break;
}
nested_switch1() {
switch (enumTwo)
{
case A:
enumTwo = EnumTwo.B;
break;
case C:
enumTwo = EnumTwo.D;
break;
default:
break;
}
switch (enumThree)
{
case AA:
enumTwo = EnumTwo.BB;
break;
case CC:
enumTwo = EnumTwo.DD;
break;
default:
break;
}
break;
}
nested_switch2() {
switch(EnumTwo)
{
default:
break;
}
switch (enumThree)
{
case AA:
enumTwo = EnumTwo.XX;
break;
case CC:
enumTwo = EnumTwo.YY;
break;
default:
break;
}
}
If you have integers X and Y and you need to switch on both, you can combine them in some unambiguous way and switch on the combination. For example, if y < 10:
switch (x*10+y)
{
case 0: // x == y == 0
case 1: // x ==0, y == 1
///
case 10: // x == 1, y == 0
case 11: // x == y == 1
//
}

Categories

Resources