1

Beginner here, is there a way to pass a condition into a method? For example passing (n > 1 && n < 10) and then the method can replace n with some variable.

//request an int from the user
public static int requestInt(String request, /*SOME CONDITION*/)
{
    Scanner input = new Scanner(System.in);
    System.out.println(request);
    int response;
    while (true){
        while (!input.hasNextInt()){
            System.out.println("Invalid response");
            input.next();
        }
        response = input.nextInt();
        if(/*RESPONSE DOESN'T FIT THE CONDITION*/){
            System.out.println("Invalid response");
        }else{
            return response;
        }
    }
}
caleb lee
  • 113
  • 3
  • 3
    You're looking to [pass in a function](https://docs.oracle.com/javase/8/docs/api/java/util/function/Function.html). More specifically, a function that returns a boolean, or a [Predicate](https://docs.oracle.com/javase/8/docs/api/java/util/function/Predicate.html). See [How to pass a function as a parameter in Java?](https://stackoverflow.com/q/4685563) and [Java Pass Method as Parameter](https://stackoverflow.com/q/2186931). – Aplet123 Mar 17 '21 at 19:30

2 Answers2

2

You can use a functional interface to represent the concept of a function from int → boolean. There are several in the java.util.function package that fit the bill:

  • Function<Integer, Boolean>: Represents a function that accepts one argument and produces a result.
  • IntFunction<Boolean>: Represents a function that accepts an int-valued argument and produces a result.
  • Predicate<Integer>: Represents a predicate (boolean-valued function) of one argument.
  • IntPredicate: Represents a predicate (boolean-valued function) of one int-valued argument.

I've listed them in order from most generic to most specialized. Let's use the last one, IntPredicate, since it represents exactly what you want, a test using an integer:

public static int requestInt(String request, IntPredicate predicate) {
    // ...

    if (predicate.test(response)) {
        return response;
    }
    else {
        System.err.println("Invalid response");
    }
}

Calling would look like this, using lambda syntax:

requestInt(request, n -> (n > 1 && n < 10));
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
-2

Okay so it's not exactly that easy, but it's still not that difficult.

private int someMethod(bool condition) {
  if (condition) {
    // Do your code
  } else {
    return -1; // -1 because that's typically used to denote invalid, but you can use null or anything else really.
  }
}