21.3k views
1 vote
After the loop terminates, it prints out, on a line by itself and separated by spaces, the sum of all the even integers read, the sum of all the odd integers read, a count of the number of even integers read, and a count of the number of odd integers read, all separated by at least one space. Declare any variables that are needed. Assume the availability of a variable, stdin, that references a Scanner object associated with standard input. That is, stdin = new Scanner(System.in); is given.

User Iyvin Jose
by
5.3k points

1 Answer

6 votes

Answer:

import java.util.Scanner;

public class OddEven

{

public static void main(String[] args) {

int sumOfEven = 0, sumOfOdd = 0, countOfEven = 0, countOfOdd = 0;

Scanner stdin = new Scanner(System.in);

while(true) {

System.out.print("Enter a number: ");

int number = stdin.nextInt();

if (number > 0) {

if (number % 2 == 0) {

sumOfEven += number;

countOfEven++;

}

else if (number % 2 == 1) {

sumOfOdd += number;

countOfOdd++;

}

}

else

break;

}

System.out.println(sumOfEven +" "+sumOfOdd+" "+countOfEven+" "+countOfOdd);

}

}

Step-by-step explanation:

- Initialize the variables

- Create a while loop that iterates until the user enters 0 (Since the terminating condition is not really specified, I chose that)

Inside the loop:

- Ask the user to enter integers

- If the number is even, add it to the sumOfEven and increment countOfEven by 1

- If the number is odd, add it to the sumOfOdd and increment countOfOdd by 1

Then:

- Print out the values as requested

User Jeremy Likness
by
5.2k points