Skip to content
Advertisement

What code solution to these ranges in java [closed]

Hello I would like to make a method that takes a given weight and windspeed and picks the right kite. The tricky part is the ranges. Any idea. I was thinking either if-else or a switch ? Picture of table I wanna code

Ive tried:

 if((5<wind && wind<10) && (40 < weight && weight< 50)){
            txt_kite.setText( "10-11 m^2");
        }
        else if((5<wind && wind<10) && (50 < weight && weight< 60)){
            txt_kite.setText( "11-12 m^2");
        }

Advertisement

Answer

You can nest the ifs to avoid having to check the wind every time. Also keep in mind that in your example code it doesn’t handle it when someone is exactly weight 50 so you need to include it in either case. I would also just let the function just return the String and use that function in the setText. So you get

public static String getKite(int wind, int weight) {
    if (5 < wind && wind <= 10) {
        if (40 < weight && weight <= 50) return "10-11 m^2";
        if (50 < weight && weight <= 60) return "11-12 m^2";
        //the rest of the weights
    } else if (7 < wind && wind <= 12) {
        if (40 < weight && weight <= 50) return "8-9 m^2";
        //all with this wind
    }
    // add the other winds here

    return "no kite possible";
}

and do

txt_kite.setText(getKite(wind, weight));

there where you want it. Also keep in mind that with this code at wind 8 for example it would pick the 5-10 category and not the 7-12. I don’t know which one should be prioritized since the table has these overlapping ranges.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement