SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Michael T. Goodrich, Roberto Tamassia, Michael H. Goldwasser
Chapter:
Java Primer
Exercise:
Exercises
Question:4 | ISBN:9781118771334 | Edition: 6

Question

Write a short Java method, isEven, that takes an int i and returns true if and only if i is even. Your method cannot use the multiplication, modulus, or division operators, however.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

package java_problems_datastructures;

import java.util.Scanner;

public class EvenTest {
	
	/* use for loop to check if it is even number or not
	   by default set isItEven variable to false
	   start the loop with i value 1
	   it change the value of boolean variable every time it entered the loop.
	   fixes the variable when for loop terminates
	*/
	public static boolean isEven(long value) {
		boolean isItEven = false;
		for (int i = 1; i < value; i++)
			isItEven = !isItEven;

		return isItEven;
	}

	public static void main(String args[]) {

		// take input from the user
		Scanner input = new Scanner(System.in);

		System.out.print("Enter a number:");
		Long userInput = input.nextLong();

		boolean check = isEven(userInput);

		if (check == true) {

			System.out.println(+userInput + " is even number");
		} else {

			System.out.println(+userInput + " is not an even number");
		}
		input.close();
	}
}

 

1 0

Discussions

Post the discussion to improve the above solution.