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:12 | ISBN:9780136091813 | Edition: 2

Question

Write a method called getGrade that accepts an integer representing a student’s grade in a course and returns that student’s numerical course grade. The grade can be between 0.0 (failing) and 4.0 (perfect). Assume that scores are in the range of 0 to 100 and that grades are based on the following scale:

For an added challenge, make your method throw an IllegalArgumentException if the user passes a grade lower than 0 or higher than 100.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Program:

public class Ch04Ex12
{
	public static void main(String[] args)
	{
		System.out.println("getGrade(26): " + getGrade(26));
		System.out.println("getGrade(62): " + getGrade(62));
		System.out.println("getGrade(97): " + getGrade(77));
		System.out.println("getGrade(97): " + getGrade(97));
	}

	public static double getGrade(int score)
	{
		if (score < 0 || score > 100)
		{
			throw new IllegalArgumentException("Invalid score.");
		}
		
		if (score < 60)
		{
			return 0.0;
		}
		else if (score <= 62)
		{
			return 0.7;
		}
		else if (score <= 94)
		{
			double grade = 0.8;

			for (int i = 63; i < score; i++)
			{
				grade += 0.1;
			}

			return Math.round(grade * 10.0) / 10.0;
		}
		else
		{
			return 4.0;
		}		
	}
}

Output:

getGrade(26): 0.0
getGrade(62): 0.7
getGrade(97): 2.2
getGrade(97): 4.0

 

0 0

Discussions

Post the discussion to improve the above solution.