Java字符串练习之比较大小,升序输出

字符串练习题的收获:使用方法较少时代码复杂,使用方法较多时代码简单(不用白不用~)


        题目:编写程序,从命令行输入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);
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值