0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Math.max()を活用してみる

Posted at

今回の問題

条件判定に関する問題。
入力された値(縦・横・高さ、l1~l5の定数)に対し、以下の条件判定を行う。

問題文から一部引用
高さが l_1 cm 以下の場合
縦と横の長い方の長さが l_2 以下の場合・・・m_1(円) //ココ
縦と横の長さの和が l_3 以下の場合・・・m_2(円)
それ以外の場合・・・m_3(円)

当初のコード

縦と横の長い方の長さを求める際、if文を使って以下のように書いていました。

if (height <= l1){
            if(length <= l2
                || width <= l2){//ココ
                    System.out.println(m1);
                }else if(length + width <= l3){
                    System.out.println(m2);
                }else{
                    System.out.println(m3);
                }
        }

縦横両方を比較するという少し冗長な方法を使っていたため、もっとシンプルにできるかもしれないと感じました。

Math.max()とは

Math.max() は、与えられた数値の中から最大のものを返すメソッドです。この関数を使うことで、条件分岐を簡潔に記述することができます。

Math.max(a,b)//a,bのうち大きいほうを返却

修正後のコード

if (height <= l1){
            if(Math.max(length,width) <= l2){//ココ
                    System.out.println(m1);
                }else if(length + width <= l3){
                    System.out.println(m2);
                }else{
                    System.out.println(m3);
                }
        }

メソッドに縦横の数値を渡し、返却値(引数のうち大きいほう)とl2を比較するコードです。
比較回数を減らすことができ、よりシンプルになりました。

3つの引数を比較したい場合

Math.max()は、引数2つに対応したメソッドです。
3つの引数を比較したい場合は、単純にメソッドを二回使えばよいです。

if (height <= l1){
            //縦、横、高さの最大値を比較したい場合
            if(Math.max(Math.max(length,width),height) <= l2){//ココ
                    System.out.println(m1);
                }else if(length + width <= l3){
                    System.out.println(m2);
                }else{
                    System.out.println(m3);
                }
        }

まとめ

Math.max()を使うことで、複雑な比較を一行で書くことができ、コードの可読性保守性が向上します。
シンプルで効率的なコードを書けるよう、今後活用していきたいと思います!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?