java中数组进行字母排序吗,Java,按字母顺序排序字符串,不带数组

So I have another assignment to do and the task is to assort 3 strings alphabetically using the compareTo method. Basically the program receives 3 strings (a, b, and c) from a tester class and its supposed to return back the "getMin", "getMiddle", and "getMax".

I figured out the getmin and max, seemed easy but im having problems with the getMiddle.

this is what i have for min and max:

String min = "";

if (a.compareTo(b) <= 0 && a.compareTo(c) <= 0) min = a;

else if (b.compareTo(a) <= 0 && b.compareTo(c) <= 0) min = b;

else if (c.compareTo(b) <= 0 && c.compareTo(a) <= 0) min = c;

return min;

and similarly for get max only slightly different. How can I go about creating the getMiddle. Also we are not allowed to use arrays as we "haven't learned" them yet. and the prof said that the code for get middle should be around 5-6 lines.

Thanks

解决方案

Multiply return values of compareTo method.

If the value is middle, results of compareTo method have different signs.

do multiply result is zero or has negative sign.

String getMiddle(String a,String b,String c)

{

String middle = "";

if (a.compareTo(b)*a.compareTo(c) <= 0) middle = a;

else if (b.compareTo(a)*b.compareTo(c) <= 0) middle = b;

else if (c.compareTo(b)*c.compareTo(a) <= 0) middle = c;

return middle;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值