Advertisement
Ligh7_of_H3av3n

06. Find Evens or Odds

May 27th, 2024
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.31 KB | None | 0 0
  1. package Lekciq;
  2.  
  3. import java.util.Scanner;
  4. import java.util.function.IntPredicate;
  5. import java.util.stream.IntStream;
  6.  
  7. public class FindEvensOrOdds {
  8.     public static void main(String[] args) {
  9.         Scanner scanner = new Scanner(System.in);
  10.  
  11.  
  12.         // Read lower and upper bounds
  13.         int lowerBound = scanner.nextInt();
  14.         int upperBound = scanner.nextInt();
  15.         scanner.nextLine(); // Consume newline
  16.  
  17.         // Read command
  18.         String command = scanner.nextLine();
  19.  
  20.         // Define predicate based on command
  21.         IntPredicate predicate;
  22.         if (command.equals("even")) {
  23.             predicate = number -> number % 2 == 0;
  24.         } else if (command.equals("odd")) {
  25.             predicate = number -> number % 2 != 0;
  26.         } else {
  27.             throw new IllegalArgumentException("Invalid command: " + command);
  28.         }
  29.  
  30.         // List numbers in the range based on the predicate
  31.         listNumbers(lowerBound, upperBound, predicate);
  32.     }
  33.  
  34.     // Method to list numbers in the range based on the predicate
  35.     private static void listNumbers(int lowerBound, int upperBound, IntPredicate predicate) {
  36.         IntStream.rangeClosed(lowerBound, upperBound)
  37.                 .filter(predicate)
  38.                 .forEach(num -> System.out.print(num + " "));
  39.     }
  40. }
  41.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement