My program suppose to get mark from user for each subject using this conditional statement. And the output is the subject's grade and the total GPA for four subjects.
I want to use this conditional statement for other four variable (subjectA,subjectB,subjectC,subjectD) replacing "discrete". And I want to access them for output. Is there any way to shorten the code instead of writing the same conditional statement for each variable ?
if (discrete>=90 && discrete <=100)
{discreteGrade= "A+" ;
discreteGPA=4.00;}
else if (discrete>=80 && discrete <=89)
{discreteGrade= "A" ;
discreteGPA=4.00;}
else if (discrete>=75 && discrete <=79)
{discreteGrade= "A-" ;
discreteGPA=3.67;}
else if (discrete>=70 && discrete <=74)
{discreteGrade= "B+" ;
discreteGPA=3.33;}
else if (discrete>=65 && discrete <=69)
{discreteGrade= "B" ;
discreteGPA=3.00;}
else if (discrete>=60 && discrete <=64)
{discreteGrade= "B-" ;
discreteGPA=2.67;}
else if (discrete>=55 && discrete <=59)
{discreteGrade= "C+" ;
discreteGPA=2.33;}
else if (discrete>=50 && discrete <=54)
{discreteGrade= "C" ;
discreteGPA=2.00;}
else if (discrete>=45 && discrete <=49)
{discreteGrade= "C-" ;
discreteGPA=1.67;}
else if (discrete>=40 && discrete <=44)
{discreteGrade= "D+" ;
discreteGPA=1.33;}
else if (discrete>=35 && discrete <=39)
{discreteGrade= "D" ;
discreteGPA=1.00;}
else
{discreteGrade= "F" ;
discreteGPA=0.00;}
So, I would try to avoid such IF-ELSE statements. They are really hard to understand, write and extend. Here is a better solution.
public class Grade {
private double min;
private double gpa;
private String mark;
public Grade(double min, double gpa, String mark) {
this.min = min;
this.gpa = gpa;
this.mark = mark;
}
}
This stores the minimum discrete needed to obtain it, the GPA and the string representation (A+, A, A-, etc.)
Now, we have a Grader class that calculates the grade. Sorry if my English is not on par and the naming are not correct, but I hope you get the point.
public class Grader {
private List<Grade> grades = Arrays.asList(new Grade(90, 4.00, "A+"),
new Grade(80, 4.00, "A"),
new Grade(75, 3.67, "A-"));
public Grade getGrade(double discrete) {
Iterator<Grade> iterator = grades.listIterator();
Grade grade = iterator.next();
while (grade.getMin() > discrete) {
grade = iterator.next();
}
return grade;
}
}
Some improvements can be done here (for example, negative or invalid marks received, but this is just a proof of concept). What it does, it iterates the list of possible grades until it gets to the correct one. Just make sure you add all the possible grades in the list. I only added the first three.
Now, the class Grader does not care for what subject it receives the grade. You can call it multiple times like this:
Grader grader = new Grader();
Grade forSubjectA = grader.grade(discreteForA);
Grade forSubjectB = grader.grade(discreteForB);
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With