Search code examples
javamethodsreturn

Java beginner exercise with methods


I am real beginner in Java and I have one simple exercise where I need to convert m/h into km/h using a method and a return from it.

I have to define 2 situations: if km/h < 0 return -1 (error) and if km/h > 0 return km/h * 1.609 (value in m/h).

I tried everything I could think of but I either get a no return statement error or no output when I try to run it.

I can't understand why even if I gave it more than one return option it just doesn't work whatever the value is. I could use System.outprintln or String but the exercise specify I must use a return method.

here is my code, written in IntelliJ:

package EXERCISE;

public class Main {

    public static void main(String[] args) {
        toMilesPerHour(0);
    }

    public static double toMilesPerHour(double kilometersPerHour) {

        if (kilometersPerHour < 0) {
            return -1;
        }
        else if (kilometersPerHour > 0) {
            return kilometersPerHour * 1.609d;
        }
        else if (kilometersPerHour == 0) {
            return 0;
        }

        return kilometersPerHour * 1.609;

        // if I don't write return here it gives me no return statement error,
        // if I write it, it gives me no output with value > or < 0 but no error.
    }

}

Solution

  • Even if you use a method, you have to print the returned value:

    package EXERCISE;
    
    public class Main {
    
        public static void main(String[] args) {
    
            System.out.println(toMilesPerHour(0));
    
        }
    
        public static double toMilesPerHour(double kilometersPerHour) {
    
            if (kilometersPerHour < 0) {
                return -1;
            }
            else if (kilometersPerHour > 0) {
                return kilometersPerHour * 1.609d;
            }
            else if (kilometersPerHour == 0) {
                return 0;
            }
            return kilometersPerHour * 1.609;
            //if I don't write return here it gives me no return statement error,
            //if I write it, it gives me no output with value > or < 0 but no error.
        }
    }
    

    Furthermore, you can get rid of the return statement at the end:

        public static double toMilesPerHour(double kilometersPerHour) {
            if (kilometersPerHour < 0) {
                return -1;
            }
            else {
                // you don't need to check if kilometersPerHour is 0, since every number multiplied with 0 is 0
                return kilometersPerHour * 1.609;
            }
        }