Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.util.*;
- /*
- 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
- */
- public class BoysGirls {
- public static void main(String[] args) {
- boyGirl();
- }
- public static void boyGirl() {
- try {
- Scanner input = new Scanner(new File("boygirl.txt"));
- int boySum = 0;
- int girlSum = 0;
- int count = 0;
- int diff = 0;
- while (input.hasNext()) {
- int x = input.nextInt();
- if (count % 2 == 0) {
- boySum += x;
- } else {
- girlSum += x;
- }
- count++;
- }
- diff = Math.abs(boySum - girlSum);
- System.out.println("Difference between boys' and girls' sums: " + diff);
- } catch (FileNotFoundException e) {
- System.out.println("error");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment