AP Computer Science Exam Question:
Write a Java program that simulates a grading system for a class. The program should prompt the user to enter the student's name and their exam score. The program should then calculate the corresponding letter grade based on the following grading scale:
Your program should display the student's name, their exam score, and the corresponding letter grade.
Write the code for the gradeCalculator
method that takes in the student's name (a String
) and their exam score (an int
) and returns a String
with the formatted output.
Your program should include proper control flow statements using if-else-if
statements.
Provide your code solution along with a step-by-step explanation of how it works.
Example Input:
Name: John Doe
Exam Score: 78
Example Output:
John Doe scored a 78, which corresponds to a C.
Code Solution:
public class GradeCalculator {
public static void main(String[] args) {
String name = "John Doe";
int score = 78;
String output = gradeCalculator(name, score);
System.out.println(output);
}
public static String gradeCalculator(String name, int score) {
String grade;
if(score >= 90) {
grade = "A";
} else if(score >= 80) {
grade = "B";
} else if(score >= 70) {
grade = "C";
} else if(score >= 60) {
grade = "D";
} else {
grade = "F";
}
String output = name + " scored a " + score + ", which corresponds to a " + grade + ".";
return output;
}
}
Step-by-Step Explanation:
We start by declaring a String
variable name
and an int
variable score
. These variables represent the student's name and exam score, respectively.
We then call the gradeCalculator
method and pass in the name
and score
variables.
Inside the gradeCalculator
method, we declare a String
variable grade
to store the calculated grade.
We use control flow statements to compare the score
variable to different thresholds.
If the score
is greater than or equal to 90, we assign the value "A" to grade
. If not, we move to the next condition.
If the score
is greater than or equal to 80 (and not in the A range), we assign the value "B" to grade
. If not, we move to the next condition.
We continue this process for the remaining grade ranges (C, D, and F), assigning the corresponding value to grade
based on the condition being true.
If none of the conditions are satisfied, i.e., the score is less than 60, we assign the value "F" to grade
.
Finally, we construct a formatted output string by concatenating the name
, score
, and grade
variables.
We return the output
string to the calling method.
In the main
method, we assign the example inputs ("John Doe"
and 78
) to the name
and score
variables.
We call the gradeCalculator
method, passing in the name
and score
variables.
The output of the gradeCalculator
method is stored in the output
variable.
We print the output
variable, displaying the formatted grade information.
This program demonstrates control flow using if-else-if
statements to calculate the letter grade based on the provided score.