Practice Midterm Exam – Monday/Wednesday Version This program will ONLY contain
ID: 3725628 • Letter: P
Question
Practice Midterm Exam – Monday/Wednesday Version
This program will ONLY contain a driver class (no domain class). Write a program that will do the following tasks:
Define 3 global int variables called sumOfEvens, countOfEvens, and usersInput, and initialize them to 0.
Hint: public static …;
In main, call 2 methods: processAllEvens() and display ();
Task #2:
In the processAllEvens() method, ask the user to give you a number between 5 and 10, and store it in usersInput. Create a loop that will accumulate all the numbers between 1 and the number entered by the user into sumOfEvens, including 1 and the number itself, but ONLY if the number is even.
Additionally, for each number that you accumulate, add 1 to the countOfEvens, so that at the end of the loop you will know how many even numbers were between 1 and the number the user entered.
Task #3:
In the display () method, print the following messages:
“There were x number of even numbers between 1 and y.”
(where x is the countOfEvens, and y is the usersInput).
“The sum of those even numbers is w.”
(where w is the sumOfEvens).
“The average of those odd numbers is z.”
(where z is the average of the sumOfEvens divided by countOfEvens).
Hint: Be careful about integer division.
Explanation / Answer
ProcessAllEvensTest.java
import java.util.Scanner;
public class ProcessAllEvensTest {
public static void main(String[] args) {
processAllEvens();
}
public static void processAllEvens() {
Scanner scan = new Scanner(System.in);
int sumOfEvens=0,countOfEvens = 0;
System.out.println("Enter a number between 5 and 10:");
int usersInput = scan.nextInt();
for(int i=1;i<=usersInput;i++) {
if(i%2 == 0) {
sumOfEvens+=i;
countOfEvens++;
}
}
display (sumOfEvens, usersInput,countOfEvens) ;
}
public static void display (int sumOfEvens, int usersInput, int countOfEvens) {
System.out.println("There were "+countOfEvens+" number of even numbers between 1 and "+usersInput+".");
System.out.println("The sum of those even numbers is "+sumOfEvens+".");
System.out.println("The average of those even numbers is "+(sumOfEvens/countOfEvens));
}
}
Output:
Enter a number between 5 and 10:
10
There were 5 number of even numbers between 1 and 10.
The sum of those even numbers is 30.
The average of those even numbers is 6
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.