有什么更好的例子可以代表 Java 中的 switch 语句? [英] In what better example can represent a switch statement in Java?

查看:14
本文介绍了有什么更好的例子可以代表 Java 中的 switch 语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我确信有比我更好的例子:)

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

推荐答案

如果你想拥有比 HashMap 更大的灵活性(不是解决方案有什么问题),你可以使用责任链:

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?");
      }
   }
}

这个看起来不多,但是checkScore方法可以执行其他检查;例如,您可以设置一系列值而不是单个 points 整数等.

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.

这篇关于有什么更好的例子可以代表 Java 中的 switch 语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆