views:

169

answers:

5

I'm sure there are better examples than mine:)

Let's say that it's snowing and the users can earn points for each snowflake, but they have to do it fast to no get stuck in the snow, so this is my ex:

class apples{
    public static void main(String args[]){
        int points;
        points = 1;

        switch (points){
        case 1:
            System.out.println("32");
            break;
        case 2:
            System.out.println("Almost half");
            break;
        case 3:
            System.out.println("You're near");
            break;
        case 4:
            System.out.println("Congratulations., You got 100 points");
        default:
            System.out.println("Want to start again?");
        break;  
        }
    }
}
A: 

Use a dictionary or a hashmap to map the number of points to the string.

Ikke
Or even a list in this case.
Joey
@ lkke show a example
+3  A: 

The switch statement has been miss-used for a long time.

The original idea was to have an entry point system; a goto-like statement which worked like this :

If my value is 1; goto 1;
Else If my value is 2; goto 2;
Else If my value is 3; goto 3;
Else If goto default;
label 1 : ...;
label 2 : ...;
label 3 : ...;
label default : ...;

And people started to like this system and decided that it would be better than having a lot of if/else statements. So they used a little trick, the break; And now people really enjoy the switch as a replacement of the if/else by breaking every case of the switch.

To have a really good example of the original switch statement, you should have something like this:

public void printDaysLeftUntilNextMonday(){
    switch(dayOfWeek){
        case 1 :
            System.out.println("Monday");
        case 2 :
            System.out.println("Tuesday");
        case 3 :
            System.out.println("Wednesday");
        case 4 :
            System.out.println("Thursday");
        case 5 :
            System.out.println("Friday");
        case 6 :
            System.out.println("Saturday");
        case 7 :
            System.out.println("Sunday");
    }
}

I had a real use case on day (rare thing if you don't abuse of break; in switch) it was in a Hangman.

public void printHangman(){
    switch(triesLeft){
        case 1 :
            printLeftLeg();
        case 2 :
            printRightLeg();
        case 3 :
            printLeftArm();
        case 4 :
            printRightArm();
        case 5 :
            printBody();
        case 6 :
            printHead();
    }
}
Colin Hebert
Unfortunatly, in Java, if dayOfWeek == 1, then it will output all the days of the week. This is not helping.
Yanick Rochon
If we're monday, you will see all the days to next monday (@see method name). I added a second example more precise.
Colin Hebert
I tried to run it in Eclipse and is not working :(
don't forget the `break;` statements
Andreas
@vili82 what part doesn't work ? It's a simple use case, it's not intended to really run as is.@Andreas that's the point
Colin Hebert
I put the break; statements and is not work ., can you try to run this code ?
@vili82 Did you put in a class?
moxn
where ? what class ? in the beginning class apples{ etc .??
+4  A: 

If you want to have more flexibility than a HashMap (not that there's anything wrong with the solution), you can go with a chain of responsibility :

class PointScore {
   private PointScore next;
   private int points;
   private String msg;

   public PointScore(int points, String msg) {
      this.points = points;
      this.msg = msg;
      this.next = null;
   }

   public PointScore setNext(PointScore next) {
      this.next = next;
      return next;
   }

   public boolean checkScore(int points) {
      if (this.points == points) {
         System.out.println(this.msg);
         return true;
      } else if (null != next) {
         return next.checkScore(points);
      } else {
         return false;
      }

   }

}

Then your main entry point :

class Apples {

   public static void main(String...args) {
      int points;
      points = 1;

      // set first condition (highest priority first)
      PointScore scores = new PointScore(4, "Congratulations., You got 100 points");
      // set next chain members in order or priority (highest to lowest)
      scores.setNext(new PointScore(3, "You're near"))
         .setNext(new PointScore(2, "Almost half"))
         .setNext(new PointScore(1, "32"));

      if (!scores.checkScore(points)) {
         System.out.println("Want to start again?");
      }
   }
}

This doesn't look much, but the checkScore method can perform other checks; for example, you could setup a range of values instead of a single points integer, etc.

Yanick Rochon
He gives me a error in eclipse with:if (this.points = points){.., i don't now way
LOL typo, it should be == , I fixed it :) I wrote that in the textarea without testing it
Yanick Rochon
Still not working http://yfrog.com/69trp1p
I don't know what you did, but I just tried it (for the first time) and it printed out 32. The screenshot you give shows that you have an error somewhere, but I don't know what it is. My best guess is that your file is named 'apples.java' and it should be 'Apples.java' since class names should start with an upper case letter and a source file must be named as one of the contained class name.
Yanick Rochon
Thanks Yanick., i tried again
just noticed I had a problem when creating the chain, my mistake. I've updated the answer.
Yanick Rochon
Yanick is not work ., can you attach a screeanshot to see that you run this code
just create Apples.java and copy/paste all the code inside. There's nothing more to it
Yanick Rochon
I run it again and the same error http://yfrog.com/mserw1p ., Can you attach a screenshot to se that this code is working in you console ?thanks
please also copy the PointScore class below your class Apples, or even better, create another file (PointScore.java - case sensitive) in the same package.
Yanick Rochon
here is your code http://yfrog.com/5nsqa1p and when i run it still give me the same error http://yfrog.com/16sqa2p
your launch configuration may still have 'apples' as startup class. You need to change it. I usually right click on the class to run (Apples.java) and select "Run as..." > "Java application"
Yanick Rochon
A: 

Okay here we go. At work we often use enum types, simple example:

public enum Colors {
   RED,
   GREEN,
   BLUE,
   YELLOW,
   VIOLET,
   BROWN,
   ORANGE; // more to come
} 

so we can switch over these literal constants:

public String colorToMood(final Colors color) {
    String mood = "everything the same to me";
    switch (color) {
      case RED:
        mood = "excited";
        break;
      case YELLOW:
        mood = "I like the sun";
        break;
      case GREEN:
        mood = "forests are nice";
        break;
      case BLUE:
        mood = "I feel free like a bird in the sky";
        break;
      // fill in your code here for VIOLET, BROWN, ORANGE
      // otherwise they get handled by the default clause
      default:
        mood = "I don't know your color";
        break;
    }
    return mood;
}

Maybe you now get a better idea what the benefits of a switch in conjunction with enums are. You can even define a constructor for your enum constants, but that gets too advanced...

Andreas
Where you run this code ? Because i tried and is not working
Of course this code will not work for you. You have to have the mentioned types ready, need at least stubs for the methods seen and after all, have a second look: the method does not return anything.You could easily make your own example. I've edited my post to a simpler example.
Andreas
@ Andreas But i want to work for me ., i want to run and to test it ., i want to learn very good this leanguege ., i just started, for this reason always i ask for good respons about the codes THAT CAN BE TASTED to see and understand better how they work and all connections between them. Thanks
A: 

I find switch statements make most sense when the range of a variable is bounded. So for example the days-of-the-week example given here is fine, and the one with the enum is even better.

Bit of a no-brainer, but wikipedia has an excellent page with the history, advantages and disadvantages of the switch statement, as well as a host of examples in different languages.

Michael Clerx
Show an example Michael of switch statements that you have used
Uhm... If you don't mind shameless self-promotion you can try my article over here: http://whiteboxcomputing.com/java/enum_factory/It contains a real-life example of a switch statement about halfway down the page.
Michael Clerx
Tomorrow I see it, now I'm dead tired .. 04:00 am here