Add a count and sum variable to your program. As you process each line print the
ID: 3691337 • Letter: A
Question
Add a count and sum variable to your program. As you process each line print the line number and add the age to the sum. At the end of the program calculate and print the average age. Your output should look like this:
1. Al Fresco 75
2. Barb Dwyer 67
...
15. Ella Vader 25
16. Earl E. Bird 76
Average age is 50
people.txt file
75 Fresco, Al
67 Dwyer, Barb
55 Turner, Paige
108 Peace, Warren
46 Richman, Mary A.
37 Ware, Crystal
83 Carr, Dusty
15 Sledd, Bob
64 Sutton, Oliver
70 Mellow, Marsha
29 Case, Justin
35 Time, Justin
8 Shorts, Jim
20 Morris, Hugh
25 Vader, Ella
76 Bird, Earl E.
This is the started code and i need the output above, thanks! *working in eclipse
import java.io.*;
import java.util.*;
public class CountWords {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new File("people.txt"));
}
System.out.println();
}
}
Explanation / Answer
import java.io.*;
import java.util.*;
public class CountWords {
/**
* @param args
* @throws FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException {
Scanner input = null;
try {
input = new Scanner(new File("people.txt"));
int count = 0, sum = 0;
while (input.hasNext()) {
// count lines
count++;
// getting line of text
String line = input.nextLine();
// split line with space
String lineArr[] = line.split(" ");
// parsing to string age to int
int age = Integer.parseInt(lineArr[0]);
// add age to sum
sum += age;
// print the details
System.out.println(count + ". " + lineArr[2] + " "
+ lineArr[1].substring(0, lineArr[1].length() - 1)
+ " " + age);
}
// printing average age
System.out.println(" Average age is " + sum / count);
} catch (Exception e) {
// TODO: handle exception
} finally {
input.close();
}
}
}
people.txt
75 Fresco, Al
67 Dwyer, Barb
55 Turner, Paige
108 Peace, Warren
46 Richman, Mary A.
37 Ware, Crystal
83 Carr, Dusty
15 Sledd, Bob
64 Sutton, Oliver
70 Mellow, Marsha
29 Case, Justin
35 Time, Justin
8 Shorts, Jim
20 Morris, Hugh
25 Vader, Ella
76 Bird, Earl E
OUTPUT:
1. Al Fresco 75
2. Barb Dwyer 67
3. Paige Turner 55
4. Warren Peace 108
5. Mary Richman 46
6. Crystal Ware 37
7. Dusty Carr 83
8. Bob Sledd 15
9. Oliver Sutton 64
10. Marsha Mellow 70
11. Justin Case 29
12. Justin Time 35
13. Jim Shorts 8
14. Hugh Morris 20
15. Ella Vader 25
16. Earl Bird 76
Average age is 50
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.