PDA

View Full Version : Java program, logic error


hiethozza272
Oct 14, 2014, 05:35 PM
So I have to write a program to calculate the amount of sale an employee need to make in order for her to earn 30 000$. Her income comes from 2 sources. One of them is her base salary which is 5000$, and the other is her commission. Here is how the commission work. If her sale is from 0 - 5000, she get 8% commission. If her sale is from 5000.1 - 10,000, she get 10%. If over 10,000, she get 12%. So for example, if her sale is 25,000$, her commission will be 5000 * 8% + 5000 * 10% + 15,000 * 12% = 2,700 . In this case, she wants to earn 30,000$ including her base salary, how much sale she has to make?




import java.util.Scanner;


public class sale539 {
public static void main(String[] args){
Scanner input = new Scanner (System.in);
System.out.println("PLease enter the amount of money you want: ");
int money = input.nextInt();
int commissionwant = money - 5000;

int sale = 0;
double commissionearn = 0;


for( sale = 1 ; sale >= commissionearn; sale++ )
{
if(sale <= 5000)
{
commissionearn = sale * 0.08;}
if( sale > 5000 && sale <= 10000)
{commissionearn = 5000* 0.08 + ( sale -5000 )*0.1;}
if ( sale > 10000 )
{ commissionearn = 5000* 0.08 + 5000 *0.1 + (sale -10000)*0.12;
}


if ( commissionearn== commissionwant)
break;

}

System.out.println("The sale you need to make is " + sale + " in order to earn " + money);


}



}

CravenMorhead
Oct 15, 2014, 08:24 AM
First off, why are you using a for loop? This is a simple mathmatical equation.

You know that you will make $400 on the first $5k, $500 on the second. So

if(commissonwant < 0)
sale = 0;
else if(commissionwant <= 400 )
sale = commissionwant / 0.08;
else if( commissionwant <= 900)
sale = 5000 + (commissionwant-400)/0.1;
else
sale = 10000 + (commissionwant-900)/0.12

Don't make things more complex then they need to be. The logic error you didn't find was in the conditional of your for loop. The conditional should be the if statement before your break. You essentially made a while(1) loop and you're breaking it internally. This is REALLY bad form.