1

this is my code:

import java.text.NumberFormat;
import java.util.Scanner;

public class Main
{
    public static void main(String[] args) {
        float yearlyReturn = 200f;
        int totalGain = 0;
        int monthlyPayOut = 100000;
        int yearsWaiting = 8;
        int firstMoney = 0;
    
        float returnGet = (1 + yearlyReturn/100);
        totalGain += firstMoney;
        for (int i = 0; i < yearsWaiting; i++){
            totalGain += (monthlyPayOut * 12);
            totalGain *= returnGet;
            System.out.println(totalGain);
            if (totalGain < 0){
                totalGain = Math.abs(totalGain);
                System.out.println(totalGain);
            }
        }
    }
}

It works normally until 8th loop, and it gives a negative number. I tried to change it into positive with Math.abs but it doesn't work.

first I want to know why it gives negative number?!

and second how does Math.abs work?!

KATA
  • 13
  • 2
  • Always read the [javadoc](https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/lang/Math.html#abs(int)). –  Jan 21 '21 at 07:54
  • 1
    Probably you are overflowing the int field. Try using Dobules everywhere and see if that cures it. Math.abs() returns the input if it is positive, or the negated value if it is negative. But if you are overflowing each time that will not help – jr593 Jan 21 '21 at 07:56
  • Just tested it and he is indeed overflowing –  Jan 21 '21 at 07:57
  • Also [this](https://stackoverflow.com/questions/3001836/how-does-java-handle-integer-underflows-and-overflows-and-how-would-you-check-fo) might be helpful –  Jan 21 '21 at 07:58

0 Answers0