带有空字符串的java switch语句

问题描述 投票:1回答:1

我必须根据他们的区域,左边界或下边界对对象进行排序。当我想在它们的左边界或下边界上对它们进行排序时,我必须说排序x并排序y。当我想按区域排序时,我需要说排序。我试图通过切换方法这样做,但我不知道如何使用其中包含空字符串的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");
  }
java string switch-statement
1个回答
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");
    }
© www.soinside.com 2019 - 2024. All rights reserved.