Write a console program that asks the user to enter a number of students in a cl
ID: 3870487 • Letter: W
Question
Write a console program that asks the user to enter a number of students in a class. For each student, the program asks whether the student is male or female, and the course average for that student. When all student information has been entered, the program prints the number of male and female students and their averages. For example, How many students? 5 Is student 1 male or female (M/F)? m What is student 1's average? 85 Is student 2 male or female (M/F)? m What is student 2's average? 91 Is student 3 male or female (M/F)? f What is student 3's average? 95 Is student 4 male or female (M/F)? f What is student 4's average? 80 Is student 5 male or female (M/F)? m What is student 5's average? 88 The 3 male students average is 88 The 2 female students average is 87.5
Explanation / Answer
import java.util.Scanner;
public class StudentGenderAverage {
/**
* @param args
*/
public static void main(String[] args) {
Scanner scanner = null;
try {
scanner = new Scanner(System.in);
// declaration
int maleCount = 0, femaleCount = 0, averageMaleSum = 0, averageFemaleSum = 0;
// prompt to enter the number of students
System.out.print("How many students?");
int noOfStudents = scanner.nextInt();
// repeat reading the data upto noofstudents
for (int i = 1; i <= noOfStudents; i++) {
// prompt to enter the gender and average
System.out.print("Is student " + i + " male or female (M/F)?");
char gender = scanner.next().charAt(0);
System.out.print("What is student " + i + "'s average?");
int average = scanner.nextInt();
// check male
if (gender == 'm' || gender == 'M') {
maleCount++;
averageMaleSum += average;
} else {
femaleCount++;
averageFemaleSum += average;
}
}
// print the results
System.out.println("The " + maleCount
+ " male students average is "
+ ((double) averageMaleSum / maleCount));
System.out.println("The " + femaleCount
+ " female students average is "
+ ((double) averageFemaleSum / femaleCount));
} catch (Exception e) {
// TODO: handle exception
}
}
}
OUTPUT:
How many students?5
Is student 1 male or female (M/F)?m
What is student 1's average?85
Is student 2 male or female (M/F)?m
What is student 2's average?91
Is student 3 male or female (M/F)?f
What is student 3's average?95
Is student 4 male or female (M/F)?f
What is student 4's average?80
Is student 5 male or female (M/F)?m
What is student 5's average?88
The 3 male students average is 88.0
The 2 female students average is 87.5
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.