So basically, I am developing a program to calculate Annual and Monthly premiums for Insurance.
I am a beginners level Java Programmer. Studying Computer Science. and here is my code.
public double calculatePremium(double premium, int time, int mostExpensive, int noGadgets) { if (time == 2) { // when user hits 2 this calcualtes monthly premium if (noGadgets == 1 && noGadgets <= 500) { premium = 4.99; } if (noGadgets == 1 && noGadgets > 500 && mostExpensive <= 750) { premium = 6.15; } if (noGadgets == 1 && noGadgets > 750 && mostExpensive <= 1000) { premium = 7.50; } if (noGadgets >= 2 && noGadgets <= 3 && mostExpensive <= 500) { premium = 17.30; } if (noGadgets >= 2 && noGadgets <= 3 && mostExpensive > 500 &&mostExpensive <= 750) { premium = 6.15; } if (noGadgets >= 2 && noGadgets <= 3 && mostExpensive > 750 && mostExpensive <= 1000) { premium = 7.50; } if (noGadgets >= 4 && noGadgets <= 5 && mostExpensive <= 500) { premium = 14.99; } if ((noGadgets >= 4 && noGadgets <= 5) && mostExpensive > 500 && mostExpensive<= 750) { premium = 18.60; } if (noGadgets >= 4 && noGadgets <= 5 && mostExpensive> 750 && mostExpensive <= 1000) { premium = 21.82; } return premium; } if (time == 1) { // if user hits 1 on kbd then calculate annual premium if (noGadgets == 1 && noGadgets <= 500) { premium = 4.99 * 12.00; } if (noGadgets == 1 && noGadgets > 500 && mostExpensive <= 750) { premium = 6.15 * 12.00; } if (noGadgets == 1 && noGadgets > 750 && mostExpensive <= 1000) { premium = 7.50 * 12.00; } if (noGadgets >= 2 && noGadgets <= 3 && mostExpensive <= 500) { premium = 17.30 * 12.00; } if (noGadgets >= 2 && noGadgets <= 3 && mostExpensive > 500 && mostExpensive <= 750) { premium = 6.15 * 12.00; } if (noGadgets >= 2 && noGadgets <= 3 && mostExpensive > 750 && mostExpensive <= 1000) { premium = 7.50 * 12.00; } if (noGadgets >= 4 && noGadgets <= 5 && mostExpensive <= 500) { premium = 14.99 * 12.00; } if ((noGadgets >= 4 && noGadgets <= 5) && mostExpensive > 500 && mostExpensive <= 750) { premium = 18.60 * 12.00; } if (noGadgets >= 4 && noGadgets <= 5 && mostExpensive > 750 && mostExpensive <= 1000) { premium = 21.82 * 12.00; } return premium; } return premium; }
My lecturers advise me not to use too many IF statements, but I'm really unsure on how to get around this?
The code above is using LOADS of IF statements, and I need to make it more efficient. Could I use a loop? and if so, then how?