java - 带有空字符串的java switch语句
问题描述
我必须根据对象的区域、leftborder 或 lowerborder 对对象进行排序。当我想在它们的左边界或下边界对它们进行排序时,我必须说 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");
}
推荐阅读
- node.js - 使用预签名 URL 将文件放入 S3 存储桶在本地工作的服务器上失败
- ruby - 有没有办法访问在块外的块内定义的局部变量?
- r - 在一个国家/地区生成随机坐标
- r - 在 R 数据框中转换间隔外连接 SQL
- java - 当有大量常量时,定义常量的正确方法是什么?
- python - 将负 Sobel 梯度值转换为 0 到 6.28 范围
- laravel - 来自这个 Laravel 应用程序/ImageCache 的连接太多
- scala - 为什么在 IntelliJ 中运行 Scala 2.13 测试时出现此错误,但在 Scala 2.12 中没有?
- git - 如何在 Visual Studio 中打开另一个 GIT 分支而不需要对当前分支进行更改?
- c# - 从 Alt+Tab 隐藏 WPF 表单