Search code examples
javacomparecomparison

Taking a user imputed comparison operator directly into if statement (java)


Sorry if this is a simple issue I am new to coding and couldn't find the answer anywhere online/couldn't find the right way to word it.

So I am taking in user input for a comparison operator (==, !=, <, <=, >, >=) and then using it to figure out output.

Is it possible to directly put a user input into a if statement's comparison operator?

aka input userInputComparison and have if statement working?

if(number1 userInputComparison number2) {

}

Is there anther way to do it?

For example would it be possible to remove the redundancy in the below simplified version of my code?

BufferedReader reader =  new BufferedReader(new InputStreamReader(System.in));
String userInput = reader.readLine(); //Should be > or <
int userInputNumber = Integer.parseInt(reader.readLine());
System.out.println("RESULTS");
int[] numbers = {5, 15, 12, 7, 0};
if (userInput.equals(">")) {
   for(int i = 0; i < numbers.length; i++) {
      if(numbers[i] > userInputNumber) {
         System.out.println(numbers[i]);
      }
   }
} else if (userInput.equals("<")) {
   for(int i = 0; i < numbers.length; i++) {
      if(numbers[i] < userInputNumber) {
         System.out.println(numbers[i]);
      }
   }
} else {
   System.out.println("please enter > or <");
}

Solution

  • Directly injecting pieces of user input into your source code and have it run is very bad. It implies that a user can now run any code on your computer, which is a big security risk.

    Instead, you should keep your if statements, so that only >, <, >= and <= are allowed. The for loops inside though, can be extracted out, so you have less duplicate code.

    You do this by storing the operator in a BiPredicate<Integer, Integer>:

    BiPredicate<Integer, Integer> operator = (x, y) -> false;
    if (userInput.equals(">")) {
       operator = (x, y) -> x > y;
    } else if (userInput.equals("<")) {
       operator = (x, y) -> x < y;
    } else if
    
    ...
    
    } else {
       System.out.println("please enter > or <");
    }
    for(int i = 0; i < numbers.length; i++) {
       if(operator.test(numbers[i], userInputNumber)) {
          System.out.println(numbers[i]);
       }
    }