Write a program that demonstrate program structure of java with use of Logical class implementation.
This program defines a class called Logical that contains two methods (isEven and isOdd) to determine if a number is even or odd. The main method uses the Scanner class to read user input and then calls the isEven method to determine if the number entered by the user is even or odd. The program then outputs a message indicating whether the number is even or odd.
Note that the isOdd method uses the ! (logical NOT) operator to invert the result of the isEven method. This demonstrates the use of logical operators in Java.
// Import the Scanner class to read user input import java.util.Scanner; // Define the Logical class public class Logical { // Define a method to determine if a number is even public static boolean isEven(int num) { return num % 2 == 0; } // Define a method to determine if a number is odd public static boolean isOdd(int num) { return !isEven(num); } // Define the main method to run the program public static void main(String[] args) { // Create a Scanner object to read user input Scanner input = new Scanner(System.in); // Prompt the user to enter a number System.out.print("Enter a number: "); int num = input.nextInt(); // Determine if the number is even or odd if (isEven(num)) { System.out.println(num + " is even."); } else { System.out.println(num + " is odd."); } } }
Comments
Post a Comment