Java使用if else语句和compareTo对三个城市进行字母顺序排列

时间:2017-09-20 22:16:55

标签: java alphabetized

嗨,我很遗憾你将如何比较三件事。教科书的例子是:

Scanner input = new Scanner(System.in);

System.out.print("Enter the first city: ");
String city1 = input.nextLine();
System.out.print("Enter the second city: ");
String city2 = input.nextLine();
System.out.print("Enter the third city: ");
String city3 = input.nextLine();

if (city1.compareTo(city2) < 0)
  System.out.println("The cities in alphabetical order are:");
  System.out.println(city1);
  System.out.println(city2);

else
  System.out.println("The cities in alphabetical order are:");
  System.out.println(city2);
  System.out.println(city1);

那么你如何比较第三个和字母顺序呢?

1 个答案:

答案 0 :(得分:0)

您可以使用内置排序算法(或您自己的)排序字母,术语词典。例如,使用Collections#sortdocumentation)。请注意,String具有可比性,默认情况下使用字典顺序。这就是您不需要显式指定顺序的原因,例如使用Comparator对象。

此代码段对城市进行排序并打印出来:

List<String> cities = Arrays.asList({city1, city2, city3});
Collections.sort(cities);

System.out.println("Cities sorted lexicographical:");
for (String city : cities) {
    System.out.println(city);
}

或者如果您更喜欢使用Streams的紧凑型 Java 8 解决方案(它基本上可以回归到相同的方法,尤其是相同的排序方法):

Stream.of(city1, city2, city3).sorted().forEach(System.out::println);

请注意,String#compareTo方法也会比较字典顺序,如前所述。因此,除了使用排序算法(以聪明的方式检查compareTo的结果)之外,您还可以直接对比较进行硬编码(就像您已经尝试过的那样):

String smallestCity;
if (city1.compareTo(city2) < 0 && city1.compareTo(city3) < 0) {
    smallestCity = city1;
} else if (city2.compareTo(city1) < 0 && city2.compareTo(city3) < 0) {
    smallestCity = city2;
} else if (city3.compareTo(city1) < 0 && city3.compareTo(city2) < 0) {
    smallestCity = city3;
} else {
    throw new AssertionError("There is no strict order!");
}

String biggestCity;
if (city1.compareTo(city2) > 0 && city1.compareTo(city3) > 0) {
    biggestCity = city1;
} else if (city2.compareTo(city1) > 0 && city2.compareTo(city3) > 0) {
    biggestCity = city2;
} else if (city3.compareTo(city1) > 0 && city3.compareTo(city2) > 0) {
    biggestCity = city3;
} else {
    throw new AssertionError("There is no strict order!");
}

String middleCity;
if (city1.compareTo(smallestCity) > 0 && city1.compareTo(biggestCity) < 0) {
    middleCity = city1;
} else if (city2.compareTo(smallestCity) > 0 && city2.compareTo(biggestCity) < 0) {
    middleCity = city2;
} else if (city3.compareTo(smallestCity) > 0 && city3.compareTo(biggestCity) < 0) {
    middleCity = city3;
} else {
    throw new AssertionError("There is no strict order!");
}

方法String#compareTo如果元素相等则返回0,如果第一个元素较小,则返回< 0,如果大于第二个元素,则返回> 0 RestTemplate })。

但如上所述,排序算法以更聪明的方式执行这些检查,更少的比较。所以你应该使用一个。