带空字符串的Java switch语句

时间:2019-02-16 13:27:04

标签: java string switch-statement

我必须根据对象的面积,左边界或下边界对对象进行排序。当我想在它们的左边界或下边界对它们进行排序时,我不得不说对x和y进行排序。当我想按区域排序时,我只需要说排序即可。我试图通过switch方法来执行此操作,但是我不知道如何使用其中包含空字符串的switch方法。这就是我想要做的:

case "sort":
  System.out.println("On what do you want to sort?");
  String choice = scanner.nextLine();
  switch (choice) {
    case "x":
      Arrays.sort(g, 0, lastPos, new Comparator < Geometric > () {
        @Override
        public int compare(Geometric o1, Geometric o2) {
          if (o1.leftBorder() < o2.leftBorder()) {
            return -1;
          } else if (o1.leftBorder() > o2.leftBorder()) {
            return 1;
          } else {
            return 0;
          }
        }

      });
      break;
    case "y":
      Arrays.sort(g, 0, lastPos, new Comparator < Geometric > () {
        @Override
        public int compare(Geometric o1, Geometric o2) {
          if (o1.bottomBorder() < o2.bottomBorder()) {
            return -1;
          } else if (o1.bottomBorder() > o2.bottomBorder()) {
            return 1;
          } else {
            return 0;
          }
        }

      });
      break;
    case (""):
      Arrays.sort(g, 0, lastPos, new Comparator < Geometric > () {
        @Override
        public int compare(Geometric o1, Geometric o2) {
          if (o1.area() < o2.area()) {
            return -1;
          } else if (o1.area() > o2.area()) {
            return 1;
          } else {
            return 0;
          }
        }

      });
      break;
    default:
      System.out.println("test1");
  }

1 个答案:

答案 0 :(得分:0)

订购代码的更好方法(例如,使用Comparator的工厂),但是坚持使用代码,我认为ENUM可以解决您的问题。

public enum CHOICES {
    X, Y, AREA
}

private static CHOICES getChoice(String choice) {
    if (choice == null || choice.trim().length() == 0) {
        return CHOICES.AREA; 
    }
    try {
        return CHOICES.valueOf(choice.toUpperCase());   
    } catch (Exception e) {
        // instead to check the value, 
        // if the input fir on, if not just catch the exception and return null
        return null;
    }       
}

然后您可以像下面那样更换交换机

        //String choice = scanner.nextLine();
    CHOICES choice = getChoice(scanner.nextLine());     
    switch (choice) {       
    case X:
        //sort by X
        break;
    case Y:
        //sort by Y
        break;
    case AREA:
        //sort by area
        break;
    default:
        System.out.println("test1");
    }
相关问题