SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
Conditional Execution
Exercise:
Exercises
Question:8 | ISBN:9780136091813 | Edition: 2

Question

Write a method called printGPA that accepts a Scanner for the console as a parameter and calculates a student’s grade point average. The user will type a line of input containing the student’s name, then a number that represents the number of scores, followed by that many integer scores. Here are two example dialogues:

Enter a student record: Maria 5 72 91 84 89 78
Maria's grade is 82.8

Enter a student record: Jordan 4 86 71 62 90
Jordan's grade is 77.25
Maria’s grade is 82.8 because her average of (72 + 91 + 84 + 89 + 78) / 5 equals 82.8.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Program:

import java.util.Scanner;

public class Ch04Ex08
{
	public static void main(String[] args)
	{
		Scanner keyboard = new Scanner(System.in);

		printGPA(keyboard);
	}

	public static void printGPA(Scanner keyboard)
	{
		String name;
		int n, score;
		double sum = 0;
		double average = 0;
		
		System.out.print("Enter a student record: ");
		name = keyboard.next();
		
		n = keyboard.nextInt();
		for (int i = 0; i < n; i++)
		{
			score = keyboard.nextInt();
			sum += score;
		}

		if(n > 0)
		{
			average = sum / n;
		}
		
		System.out.println(name + "'s grade is " + average);
	}
}

Output 1:

Enter a student record: Maria 5 72 91 84 89 78
Maria's grade is 82.8

Output 2:

Enter a student record: Jordan 4 86 71 62 90
Jordan's grade is 77.25

 

0 0

Discussions

Post the discussion to improve the above solution.