Write a static method named boyGirl that takes a string of text as a parameter.
ID: 657659 • Letter: W
Question
Write a static method named boyGirl that takes a string of text as a parameter. Assume that the text represents a series of names followed by integers, and that the names alternate between boys' names and girls names. Your method should compute the sum of the boys' integers and the sum of the girls' integers separately and print them. The line could end with either a boy or girl; you may not assume that it contains an even number of names. For example, if the String contains the following text,
"JP 3 Helene 7 Jordan 14 Iva 13 Sergey 4 Marianne 9 Kenneth 6"
then your method should produce the following output:
4 boys, 3 girls
Boys sum = 26
Girls sum = 29
Explanation / Answer
import java.io.File; import java.io.IOException; import java.util.Scanner; public class Exercise1 { public static void main(String[] args) { try { Scanner input = new Scanner(new File("boyGirl.txt")); int boys = 0; int boySum = 0; int girls = 0; int girlSum = 0; while (input.hasNext()) { input.next(); boys++; boySum += input.nextInt(); if (input.hasNext()) { input.next(); girls++; girlSum += input.nextInt(); } } int totSum = Math.abs(boySum - girlSum); System.out.printf("%d boys, %d girls ", boys, girls); System.out.printf("Difference between boys' and girls' sums: %d ", totSum); } catch (IOException error) { System.out.println("Error in processing the file boyGirl.txt" + error); } } }
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.