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:1 | ISBN:9780136091813 | Edition: 2

Question

Write a method called boyGirl that accepts a Scanner that is reading its input from a file containing a series of names followed by integers. The names alternate between boys’ names and girls’ names. Your method should compute the absolute difference between the sum of the boys’ integers and the sum of the girls’ integers. The input could end with either a boy or girl; you may not assume that it contains an even number of names.

For example, if the input file contains the following text:
Erik 3 Rita 7 Tanner 14 Jillyn 13 Curtis 4 Stefanie 12 Ben 6
Then the method should produce the following console output, since the boys’ sum is 27 and the girls’ sum is 32:
4 boys, 3 girls
Difference between boys' and girls' sums: 5

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Program:

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

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

		boyGirl(input);

		input.close();
	}

	public static void boyGirl(Scanner input)
	{
		String name;
		int score;
		int count = 0;
		int boysCount = 0;
		int girlsCount = 0;
		int boysSum = 0;
		int girlsSum = 0;

		while (input.hasNext())
		{
			name = input.next();
			score = input.nextInt();

			count++;

			if (count % 2 == 1)
			{
				boysCount++;
				boysSum += score;
			}
			else
			{
				girlsCount++;
				girlsSum += score;
			}
		}

		System.out.println(boysCount + " boys, " + girlsCount + " girls");
		System.out.println("Difference between boys' and girls' sum: " + Math.abs(boysSum - girlsSum));
	}
}

Input file: boysgirls.txt

Erik 3 Rita 7 Tanner 14 Jillyn 13 Curtis 4 Stefanie 12 Ben 6

Output:

4 boys, 3 girls
Difference between boys' and girls' sum: 5

 

0 0

Discussions

Post the discussion to improve the above solution.