带空字符串的java switch语句

标签 java string switch-statement

我必须根据对象的面积、左边框或下边框对对象进行排序。当我想对它们的左边框或下边框进行排序时,我必须说 sort x 和 sort 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");
  }

最佳答案

这是订购代码的更好方法(例如使用比较器的工厂),但只是坚持您的代码,我认为 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");
    }

关于带空字符串的java switch语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54723537/

相关文章:

Java字符串解析和通过MIDI合成器播放错误

java - 如何以预定义格式表示 JSON 字符串中的键值?

string - 如何将很长的案例模式拆分成多行?

java - JPA 查询连接表

java - 是否可以让 JSmooth 显示启动画面(-splash :image. png 选项)

c++ - 使用 string.at() 或 string[]

Java If-else结构优化

Java 和调用垃圾收集器

java - 用餐哲学家、Java 和监视器 : IllegalMonitorStateException

MySQL:根据字段值进行查询 - CASE 可以帮助构建您的查询吗?