Write a method isEven that uses the remainder operator (%) to determine whether
ID: 3736873 • Letter: W
Question
Write a method isEven that uses the remainder operator (%) to determine whether an integer is even. The method should take an integer argument and return true if the integer is even and false otherwise. Incorporate this method into an application that inputs a sequence of integers (one at a time) and determines whether each is even or odo SAMPLE RUN : java EvenOrOdd Enter a number: 0 0 is even Enter y to play again, n to quit(y/n):y Enter a number:1 1 is odd Enter y to play again, n to quit(y/n):y Enter a number:-3 -3 is odd Enter y to play again, n to quit(y/n):y Enter a number:-111 111 is odd Enter y to play again, n to quit(y/n):y Enter a number:-113 -113 is odd Enter y to play again, n to quit(y/n):y Enter a number:-115 -115 is odd Enter y to play again, n to quit(y/n):y Enter a number:-118 -118 is even Enter y to play again, n to quit(y/n):y Enter a number:202 202 is even Enter y to play again, n to quit(y/n):y Enter a number:7 7 is odd Enter y to play again, n to quit(y/n):nExplanation / Answer
import java.util.Scanner;
class Main {
// Method that returns true or false
public static boolean isEven(int n)
{
// if even, returning true
if(n%2 == 0)
return true;
// if not even, returning false
return false;
}
public static void main(String[] args) {
// declaring variables
int n;
Scanner sc = new Scanner(System.in);
// taking user input for the first time
System.out.print("Enter a number: ");
n = sc.nextInt();
while(true)
{
// calling above method to print output
if(isEven(n) == true)
{
System.out.println(n+" is even");
}
else
{
System.out.println(n+" is odd");
}
// asking for choice of doing again
System.out.print("Enter y to play agin, n to quit(y/n): ");
char choice = sc.next().charAt(0);
// breaking if no
if(choice == 'n')
{
break;
}
// else, asking for input again
System.out.print(" Enter a number: ");
n = sc.nextInt();
}
}
}
/* SAMPLE OUTPUT
Enter a number: 0
0 is even
Enter y to play agin, n to quit(y/n): y
Enter a number: 1
1 is odd
Enter y to play agin, n to quit(y/n): y
Enter a number: -3
-3 is odd
Enter y to play agin, n to quit(y/n): y
Enter a number: -111
-111 is odd
Enter y to play agin, n to quit(y/n): y
Enter a number: -115
-115 is odd
Enter y to play agin, n to quit(y/n): y
Enter a number: -118
-118 is even
Enter y to play agin, n to quit(y/n): y
Enter a number: 202
202 is even
Enter y to play agin, n to quit(y/n): y
Enter a number: 7
7 is odd
Enter y to play agin, n to quit(y/n): n
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.