aldi32
aldi32

Reputation: 19

Java - decrement variable in while loop and print list

teamsalary = 600000 avgSalindivindiv = 20000

How many team members can a team hire if their budget is 600000 and the average individual salary is 20000.

I want to print a list that looks like this:

0
1
2
3
...all the way to 30

Here is my code so far which does not work:

int teamsalary = 600000;
int avgSalindivindiv = 20000;
int numofpeople = 0;
while(teamsalary >= 0) {
    System.out.println(numofpeople);
    teamsalary = teamsalary - (numofpeople * avgSalindiv);
    numofpeople++;
    break;
}

Upvotes: 0

Views: 958

Answers (3)

Calvin P.
Calvin P.

Reputation: 1232

You can't use teamsalary = teamsalary - (numofpeople * avgSalindiv); because this will subtract 0 the first time, 20000 the second time, 40000 the third time, etc etc. You simply want to subtract 20000 each time (for each person added). You also need to keep variable names consistent. (you used both avgSalindivindiv and avgSalindiv)

int teamsalary = 600000;
int avgSalindivindiv = 20000;
int numofpeople = 0;
System.out.println(numofpeople);

// subtracting avgSalindivindiv here prevents loop from running an extra time
while((teamsalary-=avgSalindivindiv) >= 0) {
    numofpeople++;
    System.out.println(numofpeople);
}

Output:

0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

Upvotes: 1

Abdelhak
Abdelhak

Reputation: 8387

Try to remove break like this:

int teamsalary = 600000;
int avgSalindivindiv = 20000;
int numofpeople = 0;
while (teamsalary >= 0) {
    System.out.println(numofpeople);
    teamsalary = teamsalary - (numofpeople * avgSalindivindiv);
    numofpeople++;
}

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521093

The only glaring problem I see with your logic is the following line:

teamsalary = teamsalary - (numofpeople * avgSalindiv);

Here, you are subtracting the average salary multiplied by the running total number of people, which does not make sense. Instead, you want to subtract the same average avgSalindiv during each iteration of your loop. Try using this code instead:

int teamsalary = 600000;
int avgSalindivindiv = 20000;
int numofpeople = 0;
while (teamsalary >= 0) {
    System.out.println(numofpeople);
    teamsalary -= avgSalindiv;
    ++numofpeople;
}

Upvotes: 0

Related Questions