The problem I\'m working on will be utilizing a .txt file for the program\'s req
ID: 3553661 • Letter: T
Question
The problem I'm working on will be utilizing a .txt file for the program's requested File type. I've already got one written up and for your purposes please use any .txt file you wish so long as it fits the critera. Please show your whole program if possible and only responses in java, please. Thank you very much! The prompt is as follows:
Write a method called boyGirl that accepts a Scanner that reads its input from a file containing a series of names followed by integers. The names should alternate between boy's and girl's names. Your method should compute the absolute difference between the sum of boys' and girls' integers. The input could end with either a boy a girl; you may not assume that it contains an even number of names. For example, if the input file contains the following text:
Roger 5 Sandra 7 Bob 12 Jennifer 6 Caleb 8
Then the method should produce the following console output, since the boys' sum is 25 and the girls' sum is 13:
3 boys, 2 girls
Difference between boys' and girls' sums: 12
Explanation / Answer
import java.util.*; import java.io.*; public class boyGirl { public static void main(String[] args) throws FileNotFoundException { boyGirl("JP 3 Helene 7 Jordan 14 Iva 13 Sergey 4 Marianne 9 Kenneth 6"); } public static void boyGirl(String line) { Scanner input = new Scanner(line); int boys = 0; int girls = 0; int boySum = 0; int girlSum = 0; int i = 1; int diff = 0;while (input.hasNext()) { if (i%2==1) { boys++; input.next(); boySum += input.nextInt(); i++; } else { girls++; input.next(); girlSum += input.nextInt(); i++; } } diff = boySum - girlSum; System.out.println(boys + " boys, " + girls + " girls"); System.out.println("Boys sum = " + boySum); System.out.println("Girls sum = " + girlSum); System.out.println("Difference between boys' and girls' sums = " + diff); } }
import java.util.*; import java.io.*; public class boyGirl { public static void main(String[] args) throws FileNotFoundException { boyGirl("JP 3 Helene 7 Jordan 14 Iva 13 Sergey 4 Marianne 9 Kenneth 6"); } public static void boyGirl(String line) { Scanner input = new Scanner(line); int boys = 0; int girls = 0; int boySum = 0; int girlSum = 0; int i = 1; int diff = 0;
while (input.hasNext()) { if (i%2==1) { boys++; input.next(); boySum += input.nextInt(); i++; } else { girls++; input.next(); girlSum += input.nextInt(); i++; } } diff = boySum - girlSum; System.out.println(boys + " boys, " + girls + " girls"); System.out.println("Boys sum = " + boySum); System.out.println("Girls sum = " + girlSum); System.out.println("Difference between boys' and girls' sums = " + diff); } }
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.