字符串练习题的收获:使用方法较少时代码复杂,使用方法较多时代码简单(不用白不用~)
题目:编写程序,从命令行输入3个城市名,比较城市名字符串的大小,然后按从小到大的顺序输出。
分析:命令行输入,比较字符串大小,升序排序并输出
思路1(使用方法较多,代码较简单):创建字符串数组,Scanner方法输入,Arrays.sort方法升序排序,Arrays.toString方法输出
思路2(使用方法少,代码较复杂):Scanner方法输入3个城市名,compareTo方法两两比较,比较完后,if else语句执行输出
注:下列代码均在主方法内
代码:(较简单)
// 字符串数组,Arrays.sort排序,toString输出
Scanner s = new Scanner(System.in);
String[] str = { s.next(), s.next(), s.next() };
Arrays.sort(str); // 升序排序
System.out.println(Arrays.toString(str));
s.close(); // 释放s内存
代码:(较复杂)
// 用户输入
Scanner sc = new Scanner(System.in);
String city1 = sc.next();
String city2 = sc.next();
String city3 = sc.next();
sc.close(); //释放sc内存
// compareTo方法两两比较
int _1vs2 = city1.compareTo(city2);
int _1vs3 = city1.compareTo(city3);
int _2vs3 = city2.compareTo(city3);
// 比较大小,按顺序输出
if (_1vs2 > 0) // 1>2
if (_1vs3 > 0) // 1>3
if (_2vs3 < 0) // 1>3>2
System.out.println(city2 + "," + city3 + "," + city1);
else // 1>2>3
System.out.println(city3 + "," + city2 + "," + city1);
else // 3>1>2
System.out.println(city2 + "," + city1 + "," + city3);
else // 2>1
if (_2vs3 < 0) // 3>2>1
System.out.println(city1 + "," + city2 + "," + city3);
else // 2>3 2>1
if (_1vs3 > 0) // 2>1>3
System.out.println(city3 + "," + city1 + "," + city2);
else // 2>3>1
System.out.println(city1 + "," + city3 + "," + city2);