Skip to content

Instantly share code, notes, and snippets.

@TheBlackPlague
Last active April 2, 2022 15:50
Show Gist options
  • Save TheBlackPlague/5cbf61972b4a9be934208829ca0d7221 to your computer and use it in GitHub Desktop.
Save TheBlackPlague/5cbf61972b4a9be934208829ca0d7221 to your computer and use it in GitHub Desktop.
import java.util.Scanner;
public class GradeCalculator {
public static void main(String[] args) {
try (Scanner input = new Scanner(System.in)) {
while (true) {
System.out.print("Please enter your grade: ");
double grade = input.nextDouble();
if (grade > 100 || grade < 0) {
System.out.println("The grade you entered is an invalid grade. Please try again...");
continue;
}
System.out.println("Your letter grade is: " + calculateGradeOnlyMath(grade));
}
}
}
private static char calculateGradeOnlyMath(double grade) {
// Boolean mapping (100, 0) -> (1, 0)
// Map values 100 >= grade >= 60 to 1.
// Map values 60 > grade >= 0 to 0.
double booleanMap = Math.floor(grade / 60);
// A linear delta (line) that passes (60, 2) & (90, 5).
double linearDelta = (Math.min(grade, 99.99999999999999) / 10) - 4;
// Maps values like so:
// 100 >= grade >= 90: 5
// 90 > grade >= 80: 4
// 80 > grade >= 70: 3
// 70 > grade >= 60: 2
// 60 > x >= 0: 0
int normalized = (int) (booleanMap * linearDelta);
// Get the value for the ascii character by subtracting
// the normalized delta.
int asciiValue = 70 - normalized;
return (char) asciiValue;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment