gpt4 book ai didi

java - 在不使用 arraylist 的情况下使用 compareTo 在 Java 上排序

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:54:13 25 4
gpt4 key购买 nike

我是 Java 的初学者,我一直在尝试使用 compareTo 方法对三个城市进行排序。我的三个测试词是 Legion、LSD 和 Chunkey。为了识别错误,我为每个输出可能性设置了 1-6 的数字。对于输出 1,它是 (Chunkey, LSD, Legion),2 = (legion, LSD, Chunkey, 4 = (Chunkey, Legion, LSD)。当我相信我遵循正确的逻辑时,输出往往没有意义比较两个字符串,并且值为负值,然后第一个值在前,然后是第二个值。但即使这样做,它的顺序也不正确。请帮忙!谢谢!

import java.util.Scanner;
public class OrderingCity {
public static void main (String []args){
Scanner input = new Scanner(System.in);

System.out.println("Enter the First City");
String c1 = input.nextLine();
System.out.println("Enter the Second City");
String c2 = input.nextLine();
System.out.println("Enter the Third City");
String c3 = input.nextLine();

//When the value is less than 0, the first value is first while the second value is second.

//When the first city is compared to the second and if it returns a negative value (<0) then
//the first city comes first and when the value of the second city is compared to the third
//city and it returns a negative value then the second city comes before the third city
if (c1.compareTo(c2) < 0 && c2.compareTo(c3) < 0){
System.out.println(c1 + " 1 " + c2 + " " + c3);
}

//When the first city is compared to the second and it returns a positive value (>0) then
//the second city comes first and when the value of the first city is compared to the third
//city and it returns a positive value (>0) then third city comes before the first.
else if (c1.compareTo(c2) > 0 && c1.compareTo(c3) > 0){
System.out.println(c2 + " 2 " + c3 + " " + c1);
}


else if (c2.compareTo(c3) < 0 && c3.compareTo(c1) < 0){
System.out.println(c2 + " 3 " + c3 + " " + c1);
}


else if (c2.compareTo(c3) > 0 && c2.compareTo(c1) > 0){
System.out.println(c3 + " 4 " + c1 + " " + c2 );
}

else if (c3.compareTo(c1) < 0 && c1.compareTo(c2) < 0){
System.out.println(c3 + " 5 " + c1 + " " + c2);
}

else if (c3.compareTo(c1) > 0 && c3.compareTo(c2) > 0) {
System.out.println(c1 + " 6 " + c2 + " " + c3);
}


}
}

最佳答案

这应该有帮助:

import java.util.Scanner;

public class OrderingCity {
public static void main(String[] args) {

Scanner input = new Scanner(System.in);

System.out.println("Enter the First City");
String c1 = input.nextLine();

System.out.println("Enter the Second City");
String c2 = input.nextLine();

System.out.println("Enter the Third City");
String c3 = input.nextLine();

String temp;

// Example: c b a

// c > b
if (c1.compareTo(c2) > 0) {
temp = c1;
c1 = c2;
c2 = temp;
}
// b c a

// c > a
if (c2.compareTo(c3) > 0) {
temp = c2;
c2 = c3;
c3 = temp;
}
// b a c

// a > b
if (c1.compareTo(c2) > 0) {
temp = c1;
c1 = c2;
c2 = temp;
}
// a b c

System.out.printf("%s %s %s", c1, c2, c3);
}
}

关于java - 在不使用 arraylist 的情况下使用 compareTo 在 Java 上排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36503735/

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