Guest User

Boygirl exercise

a guest
Jan 3rd, 2018
169
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.42 KB | None | 0 0
  1. import java.io.*;
  2. import java.util.*;
  3.  
  4. /*
  5. Write a method called boyGirl that accepts a Scanner that is
  6. reading its input from a file containing a series of names
  7. followed by integers. The names alternate between boys’ names
  8. and girls’ names. Your method should compute the absolute
  9. difference between the sum of the boys’ integers and the sum
  10. of the girls’ integers. The input could end with either a boy
  11. or girl; you may not assume that it contains an even number
  12. of names. For example, if the input file contains the following
  13. text:
  14. Erik 3 Rita 7 Tanner 14 Jillyn 13 Curtis 4 Stefanie 12 Ben 6
  15. Then the method should produce the following console output,
  16. since the boys’ sum is 27 and the girls’ sum is 32:
  17. 4 boys, 3 girls
  18. Difference between boys' and girls' sums: 5
  19. */
  20.  
  21.  
  22. public class BoysGirls {
  23. public static void main(String[] args) {
  24. boyGirl();
  25. }
  26.  
  27. public static void boyGirl() {
  28. try {
  29. Scanner input = new Scanner(new File("boygirl.txt"));
  30. int boySum = 0;
  31. int girlSum = 0;
  32. int count = 0;
  33. int diff = 0;
  34. while (input.hasNext()) {
  35. int x = input.nextInt();
  36. if (count % 2 == 0) {
  37. boySum += x;
  38. } else {
  39. girlSum += x;
  40. }
  41. count++;
  42. }
  43. diff = Math.abs(boySum - girlSum);
  44. System.out.println("Difference between boys' and girls' sums: " + diff);
  45. } catch (FileNotFoundException e) {
  46. System.out.println("error");
  47. }
  48. }
  49. }
Advertisement
Add Comment
Please, Sign In to add comment