For research purposes and to better help students, the admissions office of your
ID: 3621487 • Letter: F
Question
For research purposes and to better help students, the admissions office of your local university wants to know how well femal and male students perform certain courses. You receive the file that contains female and male student GPAs for certain courses. Due to confidentiality, the letter code f is used for female students and m for male students. Every file entry consists of a letter code followed by a GPA. Each line has one entry. The number of entries in the file is unknown. Write a Java program that computes and outputs the average GPA for both female and male students. Format your results to two decimal places.
Explanation / Answer
import java.io.*;
import java.util.Scanner;
public class GPA
{
public static void main(String[] args) throws IOException
{
// default filename is "GPAs.txt"
// open file reader
Scanner filein = new Scanner(new File("GPAs.txt"));
// totals
double mtot = 0;
double ftot = 0;
double mnum = 0;
double fnum = 0;
// read all data
while(filein.hasNext())
{
// read M/F
char gender = filein.next().charAt(0);
// read GPA
double gpa = filein.nextDouble();
// update totals
switch(gender)
{
case 'f': case 'F':
ftot += gpa;
fnum++;
break;
case 'm': case 'M':
mtot += gpa;
mnum++;
break;
}
}
// compute averages
double mavg = mtot/mnum;
double favg = ftot/fnum;
System.out.printf("Male average GPA: %.2f ", mavg);
System.out.printf("Female average GPA: %.2f ", favg);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.