gpt4 book ai didi

带空字符串的java switch语句

转载 作者:太空宇宙 更新时间:2023-11-04 09:51:12 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com