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:
Stuart Reges, Marty Stepp
Chapter:
Conditional Execution
Exercise:
Exercises
Question:7 | ISBN:9780136091813 | Edition: 2

Question

Write a method called evenSumMax that accepts a Scanner for the console as a parameter. The method should prompt the user for a number of integers, then prompt the integer that many times. Once the user has entered all the integers, the method should print the sum of all the even numbers the user typed, along with the largest even number typed. You may assume that the user will type at least one nonnegative even integer. Here is an example dialogue: 

How many integers? 4
Next integer? 2
Next integer? 9
Next integer? 18
Next integer? 4
Even sum = 24, even max = 18

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Program:

import java.util.Scanner;
public class Ch04Ex07
{
	public static void main(String[] args)
	{
		Scanner keyboard = new Scanner(System.in);

		evenSumMax(keyboard);
	}

	public static void evenSumMax(Scanner keyboard)
	{
		int n;
		int number;
		int evenSum = 0;
		int evenMax = 0;
		
		System.out.print("How many integers? ");
		n = keyboard.nextInt();
		
		for (int i = 0; i < n; i++)
		{
			System.out.print("Next integer? ");
			number = keyboard.nextInt();
			
			if (number % 2 == 0)
			{
				evenSum += number;
				
				if(evenMax == 0)
				{
					evenMax = number;
				}
				else if (number > evenMax)
				{
					evenMax = number;
				}
			}
		}

		System.out.printf("Even sum = %d, even max = %d", evenSum, evenMax);
	}
}

Output:

How many integers? 4
Next integer? 2
Next integer? 9
Next integer? 18
Next integer? 4
Even sum = 24, even max = 18

 

0 0

Discussions

Post the discussion to improve the above solution.