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

时间:2015-01-25 18:52:00

标签: java

想要以任何顺序进入3个城市,并希望java按字母顺序显示它们。考虑使用swap选项,但认为附带的代码可以使用“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);
    }
}

3 个答案:

答案 0 :(得分:2)

您可以使用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]);
}

答案 1 :(得分:0)

试试这个:

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
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();

 ArrayList<String> cities = new ArrayList<String>();
  cities.add(city1);
  cities.add(city2);
  cities.add(city3);
  Collections.sort(cities); // Sorting the cities in alphabetical order
  System.out.println("The cities in alphabetical order are : ");
  for (String city : cities) {
       System.out.println(city);
      }

    } 
}

答案 2 :(得分:0)

您可以创建字符串列表,对其进行排序,然后迭代其内容,如下所示:

System.out.println("Enter the names of 3 cities : ");
List<String> cities =new ArrayList<>();
Scanner s = new Scanner(System.in);
    for(int x=0; x<3; x++){
    cities.add(s.nextLine());
}
 Collections.sort(cities);
 System.out.println("Cities in alphabetical order: ");
 for(String city:cities)
     System.out.print(city+" ");;
     System.out.println();
  } 
}