gpt4 book ai didi

java - 尝试按字母顺序显示 3 个随机选择的城市

转载 作者:行者123 更新时间:2023-12-02 05:02:26 25 4
gpt4 key购买 nike

想要以任意顺序输入 3 个城市,并希望 java 按字母顺序显示它们。考虑过使用交换选项,但认为随附的代码可以与“if”“else”语句一起使用。任何想法...谢谢

import java.util.Scanner;

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

// Prompt the user to enter two cities
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 && city2.compareTo(city3) < 0)
System.out.println("The cities in alphabetical order are " +
city1 + " " + city2 + " " + city3);
else
System.out.println("The cities in alphabetical order are " +
city3 + " " + city2 + " " + city1);
}
}

最佳答案

可以使用Arrays.sort(arr)方法对arr元素进行排序示例:

Scanner input = new Scanner(System.in);
String [] arr = new String[3];
// Prompt the user to enter two cities
System.out.print("Enter the first city: ");
arr[0] = input.nextLine();
System.out.print("Enter the second city: ");
arr[1] = input.nextLine();
System.out.print("Enter the third city: ");
arr[2] = input.nextLine();
Arrays.sort(arr);
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}

关于java - 尝试按字母顺序显示 3 个随机选择的城市,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28140135/

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