*4.24(对三个城市排序)编写一个程序,提示用户输入三个城市名称,然后以升序进行显示。
下面是一个运行示例:
Enter the first city:
Enter the second city:
Enter the third city:
The three cities in alphabetical order are Atlanta Chicago Los Angeles
*4.24(Sort three cities) Write a program that prompts the user to enter three cities and displays them in alphabetical order.
Here is a sample run:
Enter the first city:
Enter the second city:
Enter the third city:
The three cities in alphabetical order are Atlanta Chicago Los Angeles
下面是参考答案代码:
import java.util.*;
public class SortThreeCitiesQuestion24 {
public static void main(String[] args) {
String city1,city2,city3;
Scanner inputScanner = new Scanner(System.in);
System.out.print("Enter the first city: ");
city1 = inputScanner.nextLine();
System.out.print("Enter the second city: ");
city2 = inputScanner.nextLine();
System.out.print("Enter the third city: ");
city3 = inputScanner.nextLine();
if(city1.compareTo(city2) > 0) // city1 > city2
{
if(city2.compareTo(city3) > 0) // city2 > city3
System.out.println("The three cities in alphabetical order are " + city1 + " " + city2 + " " + city3);
else //city2 < city3
{
if(city1.compareTo(city3) > 0) // city1 > city3
System.out.println("The three cities in alphabetical order are " + city2 + " " + city3 + " " + city1);
else // city1 < city3
System.out.println("The three cities in alphabetical order are " + city2 + " " + city1 + " " + city3);
}
}
else // city1 < city2
{
if(city1.compareTo(city3) > 0) // city1 > city3
System.out.println("The three cities in alphabetical order are " + city3 + " " + city1 + " " + city2);
else //city1 < city3
{
if(city2.compareTo(city3) > 0) // city2 > city3
System.out.println("The three cities in alphabetical order are " + city1 + " " + city3 + " " + city2);
else // city2 < city3
System.out.println("The three cities in alphabetical order are " + city1 + " " + city2 + " " + city3);
}
}
inputScanner.close();
}
}
运行效果:
注:编写程序要养成良好习惯
1.文件名要用英文,具体一点
2.注释要英文
3.变量命名要具体,不要抽象(如:a,b,c等等),形式要驼峰化
4.整体书写风格要统一(不要这里是驼峰,那里是下划线,这里的逻辑段落空三行,那里相同的逻辑段落空5行等等)
5.普通变量,方法名要小驼峰,类名要大驼峰,常量要使用全部大写加上下划线命名法
6.要学习相应的代码编辑器的一些常用快捷键,如:快速对齐等等