Write a method named boyGirl that accepts a Scanner as a parameter. The Scanner
ID: 3624987 • Letter: W
Question
Write a method named boyGirl that accepts a Scanner as a parameter. The Scanner 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. If the input file tas.txt contains the following text:Steve 3 Sylvia 7 Craig 14 Lisa 13 Brian 4 Charlotte 9 Jordan 6
then your method could be called in the following way:
Scanner input = new Scanner(new File("tas.txt"));
boyGirl(input);
and should produce the following output, since the boys' sum is 27 and the girls' sum is 29:
4 boys, 3 girls
Difference between boys' and girls' sums: 2
This should be answered only in the form of basic java.
Explanation / Answer
public static void boyGirl(Scanner myScanner) { int boysSum = 0; int girlsSum = 0; int numberOfBoys = 0; int numberOfGirls = 0; boolean aBoy = true; while (myScanner.hasNext()) { if (myScanner.hasNextInt()) { if (aBoy) { boysSum += myScanner.nextInt(); numberOfBoys += 1; aBoy = false; } else //it's a girl { girlsSum += myScanner.nextInt(); numberOfGirls += 1; aBoy = true; } } else { myScanner.next(); //Read the non numeric character } } System.out.println(numberOfBoys + " boys, " + numberOfGirls + " girls"); System.out.println("Difference between boys' and girls' sums: " + Math.abs(boysSum-girlsSum)); }
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.