user407589
user407589

Reputation: 81

In what better example can represent a switch statement in Java?

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;  
        }
    }
}

Upvotes: 1

Views: 2059

Answers (5)

Andreas
Andreas

Reputation: 4009

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...

Upvotes: 0

Michael Clerx
Michael Clerx

Reputation: 3056

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.

Upvotes: 0

Yanick Rochon
Yanick Rochon

Reputation: 53606

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.

Upvotes: 4

Colin Hebert
Colin Hebert

Reputation: 93187

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();
    }
}

Upvotes: 4

Ikke
Ikke

Reputation: 101251

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

Upvotes: 0

Related Questions