javafor-loopcalculator

Why is my code outputting one more than the math?


I'm writing a loan calculator where 10% of the remaining amount of the loan is subtracted from the previous amount over the course of six months. The problem isn't difficult, it's that the code I wrote seems to be too simplistic.

import java.util.Scanner;

public class Program
{
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int amount = scanner.nextInt();
        
        int payment;

        for (int month = 0; month < 6; month++)
        {
            payment = amount / 10;
            
            amount -= payment;
        }

        System.out.println(amount);
        
    }
}

The code sort of works, but I did the math and the output of amount is exactly 1 more than it should be. Is there some kind of Java rule that I just haven't learned yet, or what?


Solution

  • Solution

    The following code will give you the result rounded on two decimal places.

    As in the commentarys already mentioned when you do 76 / 10 on an integer the result will be 7 so the decimal part will be lost.

    So in the solution below I used double instead of integer and I rounded up the result on two decimal places as you expect from currencys.

    import java.util.Scanner;
    
    public class Programm
    {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            double amount = scanner.nextDouble();
            
            double payment;
            try {
            for (int month = 0; month < 6; month++)
            {
                
                payment = amount / 10;
                
                amount -= payment;
                amount = Math.round(100.0 * amount) / 100.0;
                }
            }catch(Exception e) {
                System.out.println("Zero Divivided");
            }
    
            System.out.println(amount);
            
        }
    }
    

    For the input of 100 the code produces the result 53.15