question archive Exercise (Method): boolean method called isOdd() in a class called OddTest, which takes an int as input and returns true if the it is odd
Subject:Computer SciencePrice:2.87 Bought7
Exercise (Method): boolean method called isOdd() in a class called OddTest, which takes an int as input and returns true if the it is odd. The signature of the method is as follows:
public static boolean isOdd(int number)
Also write the main() method that prompts user for a number, and prints "ODD" or "EVEN". You should test for negative input.
Answer:
import java.util.Scanner;
public class OddTest {
public static void main(String[] args) {
// TODO code application logic here
Integer number; //for storing input
boolean result; //for storing the return value of IsOdd function
Scanner scInput = new Scanner(System.in);
System.out.print("Please enter a number: ");
number = scInput.nextInt();
result = isOdd(number);
if (result) {
System.out.println("The number is: ODD");
}
else
{
System.out.println("The number is: EVEN");
}
}
//return true if the number is odd otherwise return false
static boolean isOdd(Integer number){
number = Math.abs(number); //make the absolute value
return number%2 != 0; //check for even(divisible by 2)
}
}