Search code examples
if-statementmethodsreturn

Returning with if else statements



import java.util.Scanner;

public class PracticeQuestionWK4 {
    private static double computeDifference(double first, double second) {
        if (first <= second) {
            System.out.println("First double must be greater than second double, please try again.");
        } else {
            System.out.println(first - second);
        }
        return first - second;
    }

    public static void main(String[] args) {
        Scanner myScanner = new Scanner(System.in);
        System.out.print("Enter first double: ");
        double firstDouble = myScanner.nextDouble();
        System.out.print("Enter second double: ");
        double secondDouble = myScanner.nextDouble();
        computeDifference(firstDouble, secondDouble);
    }

}

This code feels awkward. Is there a purpose using private static double instead of private static void here? The question I'm answering calls for a return but it seems redundant. What should I do? EDIT: Sorry the question also calls for the print function to be in it too


Solution

  • It is a calculation function, you should simply use its result.

    double result = computeDifference(firstDouble, secondDouble);
    System.out.print("Result: " + result);
    

    Inside the function there normally should be no output. Conventionally for really erroneous function arguments, one should throw an exception:

    private static double computeDifference(double first, double second) {
        if (first <= second) {
            throw new IllegalArgumentException(
                    "First double must be greater than second double: "
                    + first + " and " + second);
        }
        return first - second;
    }
    

    In this case maybe check the parameters before the call.

    Using such functions should not flood the console with insensible output. (It would slow calculations too.) Throwing an exception, aborting the application, like with division by zero, is a form of fail-fast. Allowing the developer to find and repair errors fast. Here it would mean, that the input must be checked first.

    If exceptions are still not taught (assuming you are in a programmer's course), then only in the error case do a println, and return 0 or such.