Search code examples
javareturnsystem.out

Why do I get number 320.04 printed to the console in the below code?


I read the below code a lot of times and I cannot figure out why I get the 320.04 on the console. Can someone kindly help me figure out?

package com.heshanshivantha;

public class Main {

    public static void main(String[] args) {

        calcFeetAndInchesToCentimeters(126);
    }

    public static double calcFeetAndInchesToCentimeters(double feet, double inches) {
        if (feet >= 0 && inches >= 0 && inches <= 12) {
            System.out.println(feet * 12 * 2.54 + inches * 2.54);
            double centimeters = feet * 12 * 2.54 + inches * 2.54;
            System.out.println(feet + " feet " + inches + " inches = " + centimeters + " cm");
            return centimeters;
        } return -1;
    }

   public static double calcFeetAndInchesToCentimeters(double inches) {
        if (inches >= 0) {
            int feet =(int) (inches / 12);
            int remainingInches =(int) (inches % 12);
            System.out.println(inches + " inches is equal to " + feet + " feet and " + remainingInches + " inches");
            return calcFeetAndInchesToCentimeters(feet, remainingInches);
        } return -1;
   }

}

126.0 inches is equal to 10 feet and 6 inches 320.04 10.0 feet 6.0 inches = 320.04 cm

Process finished with exit code 0


Solution

  • That's because of the first line after the if condition. Remove System.out.println(feet * 12 * 2.54 + inches * 2.54); and you are done.