41.4k views
3 votes
Write a program with a method named isEven that accepts an int argument. The method should return true if the argument is even, or false otherwise. The program's main method should use a loop to generate 100 random integers. It should use the isEven method to determine whether each random number is even or odd. When the loop is finished, the program should display the number of even numbers that were generated, and the number of odd numbers. Hint: for integer n is even if there exist an integer k such that n=2k; and n is odd if there exist an integer k such that n=2k+1. The code should be able to be compiled and run - no syntax or logic errors.

User Lavinio
by
7.1k points

1 Answer

1 vote

Final answer:

To write a program that generates 100 random integers and uses a method to determine whether each number is even or odd, you can create a method called isEven and use a loop in the main method to generate and count even and odd numbers.

Step-by-step explanation:

To write a program that generates 100 random integers and uses a method to determine whether each number is even or odd, you can follow the given instructions:

  1. Create a method called isEven that accepts an int argument and returns true if the argument is even, or false otherwise.
  2. In the main method, use a loop to generate 100 random integers. For each random number, call the isEven method to determine if it is even or odd.
  3. Keep a count of the number of even and odd numbers generated.
  4. After the loop finishes, display the counts of even and odd numbers.

Here's an example implementation in Java:

import java.util.Random;

public class EvenOddCounter {

public static boolean isEven(int number) {
return number % 2 == 0;
}

public static void main(String[] args) {
Random rand = new Random();
int evenCount = 0;
int oddCount = 0;

for (int i = 0; i < 100; i++) {
int randomNum = rand.nextInt();

if (isEven(randomNum)) {
evenCount++;
} else {
oddCount++;
}
}

System.out.println("Number of even numbers: " + evenCount);
System.out.println("Number of odd numbers: " + oddCount);
}
}

User Sheikhjabootie
by
7.8k points