弱肉强食 弱肉强食 - 3 years ago 148
Java Question

Final salary does not increase in salary counter?

So I wrote a salary calculator to this lab prompt:

Write a program that displays a salary schedule for teachers. The inputs are the starting salary, the percentage increase, and the number of years in the schedule. Each line in the outputted schedule should contain the year number and the salary for that year.

import java.util.Scanner;

public class Lab2_10
{

public static void main (String[] args)
{
// Get values
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the base first year salary: ");
int first = scanner.nextInt();
System.out.println("Enter the percentage increase: ");
int percent = scanner.nextInt();
System.out.println("Enter the number of years in the schedule: ");
int years = scanner.nextInt();

// Calculate salary for each year
int total = first;
int i = 1;
int increment = percent / total * 100;
while (i <= years && years <= 25)
{
increment = percent / total * 100;
total += increment;
System.out.println(total + " " + i);
i++;
}

}
}


So that's what I have so far. However, the increment line doesn't seem to be working. When I enter 40,000 as the base salary with a 5% increase over 20 years, it returns this.

40000 1
40000 2
40000 3
40000 4
40000 5
40000 6
40000 7
40000 8
40000 9
40000 10
40000 11
40000 12
40000 13
40000 14
40000 15
40000 16
40000 17
40000 18
40000 19
40000 20


I know the year is incrementing, but the salary stays the same. I was wondering if it is an issue with the loop or with declarations? I don't really know how to fix it.

Answer Source

Your % calculation logic is incorrect

int increment = percent / total * 100;

change it to

int increment = total * percent / 100.0; // note 100.0

2 things here.

  1. Simple math
  2. Integer division
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download