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:
File Processing
Exercise:
Exercises
Question:2 | ISBN:9780136091813 | Edition: 2

Question

Write a method called evenNumbers that accepts a Scanner reading input from a file with a series of integers, and report various statistics about the integers to the console. Report the total number of numbers, the sum of the numbers, the count of even numbers and the percent of even numbers. For example, if the input file contains the following text:
5 7 2 8 9 10 12 98 7 14 20 22

Then the method should produce the following console output:
12 numbers, sum = 214
8 evens (66.67%)

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Program:

import java.util.*;
import java.io.*;

public class Ch06Ex02
{
	public static void main(String[] args) throws FileNotFoundException
	{
		Scanner input = new Scanner(new File("numbers.txt"));

		evenNumbers(input);

		input.close();
	}

	public static void evenNumbers(Scanner input)
	{
		int num;
		int numsCount = 0;
		int evensCount = 0;
		int sumOfNumbers = 0;

		while (input.hasNextInt())
		{
			num = input.nextInt();

			numsCount++;
			sumOfNumbers += num;
			if (num % 2 == 0)
			{
				evensCount++;
			}
		}

		System.out.println(numsCount + " numbers, sum = " + sumOfNumbers);
		System.out.printf("%d evens (%.2f%%)\n", evensCount, ((double) evensCount / numsCount * 100.0));
	}
}

Input file: numbers.txt

5 7 2 8 9 10 12 98 7 14 20 22

Output:

12 numbers, sum = 214
8 evens (66.67%)

 

0 0

Discussions

Post the discussion to improve the above solution.