Enter is required twice in my GPA Calculator - java

I barely started coding a couple weeks ago and have a project for my high school computer science class that requires me to make a GPA calculator. It's not the best code right now or the best technique to calculate GPA but it's a start (if someone could help clean it up and simplify it I would greatly appreciate you).
There's a problem with the code though. Every time a user input is required from the console they have to press enter twice. I feel like the solution is very easy but I am stuck on why this is happening.
import java.util.Scanner;
public class gpaCalc {
public static double gpa;
public static String grade = "";
public static double gpaTotal = 0;
public static double points = 0;
public static double numberOfClasses;
public static double class1points;
public static double class2points;
public static double class3points;
public static double class4points;
public static double class5points;
public static double class6points;
public static double class7points;
public static double class8points;
static Scanner letterGrade = new Scanner(System.in);
static Scanner numClasses = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Welcome to Adrian's GPA calculator.");
System.out.println("This program will calculate your weighted and unweighted GPA for this school year.");
classesNumber();
}
public static void classesNumber() {
System.out.println("Please enter the number of classes that you are enrolled in for the school year.");
numberOfClasses = numClasses.nextDouble(); //input is stored in variable numberOfClasses
if(numberOfClasses >= 9 || numberOfClasses < 2)
System.out.println("Are you sure you go to ECHS?");
//limit the number of classes from 2-8
if (numberOfClasses <= 8 && numberOfClasses >= 2)
System.out.println("Please enter the letter grade you have recieved in class 1 (Uppercase letters i.e. A,B,C,D,F).");
else
classesNumber(); //error occurs and doesn't reset when a letter is put and not a number
class1();
}
public static void class1() {
grade = letterGrade.next(); //unweighted GPA finder
if (grade.equals("A"))
points = 4.0;
else if (grade.equals("B"))
points = 3.0;
else if (grade.equals("C"))
points = 2.0;
else if (grade.equals("D"))
points = 1.0;
else if (grade.equals("F"))
points = 0;
else {
System.out.println("Invalid entry. Please enter a valid entry.");
class1 ();
}
class1points = points;
class2();
}
public static void class2() {
System.out.println("Please enter the letter grade you have recieved in class 2 (Uppercase letters i.e. A,B,C,D,F).");
grade = letterGrade.next();
if (grade.equals("A"))
points = 4.0;
else if (grade.equals("B"))
points = 3.0;
else if (grade.equals("C"))
points = 2.0;
else if (grade.equals("D"))
points = 1.0;
else if (grade.equals("F"))
points = 0;
else {
System.out.println("Invalid entry. Please enter a valid entry.");
class2();
}
class2points = points;
class3();
}
public static void class3() {
System.out.println("Please enter the letter grade you have recieved in class 3 (Uppercase letters i.e. A,B,C,D,F).");
grade = letterGrade.next();
if (grade.equals("A"))
points = 4.0;
else if (grade.equals("B"))
points = 3.0;
else if (grade.equals("C"))
points = 2.0;
else if (grade.equals("D"))
points = 1.0;
else if (grade.equals("F"))
points = 0;
else {
System.out.println("Invalid entry. Please enter a valid entry.");
class3();
}
class3points = points;
class4();
}
public static void class4() {
System.out.println("Please enter the letter grade you have recieved in class 4 (Uppercase letters i.e. A,B,C,D,F).");
grade = letterGrade.next();
if (grade.equals("A"))
points = 4.0;
else if (grade.equals("B"))
points = 3.0;
else if (grade.equals("C"))
points = 2.0;
else if (grade.equals("D"))
points = 1.0;
else if (grade.equals("F"))
points = 0;
else {
System.out.println("Invalid entry. Please enter a valid entry.");
class4();
}
class4points = points;
class5();
}
public static void class5() {
System.out.println("Please enter the letter grade you have recieved in class 5 (Uppercase letters i.e. A,B,C,D,F).");
grade = letterGrade.next();
if (grade.equals("A"))
points = 4.0;
else if (grade.equals("B"))
points = 3.0;
else if (grade.equals("C"))
points = 2.0;
else if (grade.equals("D"))
points = 1.0;
else if (grade.equals("F"))
points = 0;
else {
System.out.println("Invalid entry. Please enter a valid entry.");
class5();
}
class5points = points;
class6();
}
public static void class6() {
System.out.println("Please enter the letter grade you have recieved in class 6 (Uppercase letters i.e. A,B,C,D,F).");
grade = letterGrade.next();
if (grade.equals("A"))
points = 4.0;
else if (grade.equals("B"))
points = 3.0;
else if (grade.equals("C"))
points = 2.0;
else if (grade.equals("D"))
points = 1.0;
else if (grade.equals("F"))
points = 0;
else {
System.out.println("Invalid entry. Please enter a valid entry.");
class6();
}
class6points = points;
class7();
}
public static void class7() {
System.out.println("Please enter the letter grade you have recieved in class 7 (Uppercase letters i.e. A,B,C,D,F).");
grade = letterGrade.next();
if (grade.equals("A"))
points = 4.0;
else if (grade.equals("B"))
points = 3.0;
else if (grade.equals("C"))
points = 2.0;
else if (grade.equals("D"))
points = 1.0;
else if (grade.equals("F"))
points = 0;
else {
System.out.println("Invalid entry. Please enter a valid entry.");
class7();
}
class7points = points;
class8();
}
public static void class8() {
System.out.println("Please enter the letter grade you have recieved in class 8 (Uppercase letter i.e. A,B,C,D,F).");
grade = letterGrade.next();
if (grade.equals("A"))
points = 4.0;
else if (grade.equals("B"))
points = 3.0;
else if (grade.equals("C"))
points = 2.0;
else if (grade.equals("D"))
points = 1.0;
else if (grade.equals("F"))
points = 0;
else {
System.out.println("Invalid entry. Please enter a valid entry.");
class8();
}
class8points = points;
calculator();
}
public static void calculator() {
gpaTotal = (class1points + class2points + class3points + class4points + class5points + class6points + class7points + class8points ) / numberOfClasses;
System.out.println("Your unwweighted GPA is: " + gpaTotal);
}
}

Your problem should be solved by removing 1 scanner, and suggestions to your codes :
Use array to store subjects
String[] mySubjects = {"sub_1", "sub_2", "sub_3", "sub_4", ..};
Use loop to reduce repetitive
for (int i = 0; i < mySubject.length; i++) {
your_code_here;
}

Created a simplified version of your code, without need for an array.
Maybe not the best, but if you just started out, it can guide you somewhere about avoiding code repetition.
I tried to organize everything the way you did, just to help you see the code more clearly.
Maybe you can add a plus check to this code, in the classNumber() method, to avoid entering non integer values. + Split the getClassPoints() method into some parts to avoid side effects..
public static char grade;
public static double gpaTotal = 0;
public static int numberOfClasses;
static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Welcome to Adrian's GPA calculator.");
System.out.println("This program will calculate your weighted and unweighted GPA for this school year.");
classesNumber();
}
public static void classesNumber() {
System.out.println("Please enter the number of classes that you are enrolled in for the school year.");
numberOfClasses = scan.nextInt(); //input is stored in variable numberOfClasses
if(numberOfClasses >= 9 || numberOfClasses < 2)
System.out.println("Are you sure you go to ECHS?");
getClassPoints();
}
public static void getClassPoints () {
//You dont need the numberOfClasses as parameter because its static.
for (int i = 0; i < numberOfClasses; i++){
while (true){
System.out.println("Please enter the letter grade you have recieved in class " + (i + 1) +"(Uppercase letter i.e. A,B,C,D,F).");
grade = scan.next().charAt(0); //unweighted GPA finder
grade = Character.toLowerCase(grade);
if (grade == 'a'){
gpaTotal += 4;
break;
}
else if (grade == 'b'){
gpaTotal += 3;
break;
}
else if (grade == 'c'){
gpaTotal += 2;
break;
}
else if (grade == 'd'){
gpaTotal += 1;
break;
}
else if (grade == 'f'){
break;
}
System.out.println("Invalid entry. Please enter a valid entry.");;
}
}
if (gpaTotal > 0){
System.out.println("Your unwweighted GPA is: " + (gpaTotal / numberOfClasses));
}
else {
System.out.println("Too many F grade!");
}
}
}

Related

How can I prevent the user from entering the same text twice

This program basically calculates the gpa, by letting the user enter the number of courses and course code, with the relevant credit and marks. If the course code is entered twice, a message will show (the course is already registered), and it will keep looping until the user has entered all courses with a different course code
I have created two methods. One to check if the code is already registered and the other for calculating the gpa, the first method that checks the user input, I'm not sure about it. Because if I entered the course code twice it will only show the message and would allow me to calculate the rest
public static boolean checkCourse(String[] courseList, String code){
boolean check = false;
for(int i=0 ; i < courseList.length; i++){
if(code.equals(courseList[i]))
check = true;
else
check = false;
}
return check;
}
public static double gradeValue(double marks){
double grade = 1.0;
if(marks >=95){ grade = 5.0;}
else if (marks >= 90) { grade = 4.75;}
else if (marks>=85) { grade = 4.5;}
else if (marks >= 80) { grade = 4.0;}
else if (marks >= 75) { grade = 3.5; }
else if (marks >= 70) { grade = 3.0;}
else if (marks >= 65) {grade = 2.5 ;}
else if (marks >= 60) { grade = 2;}
else if (marks < 60) { grade =1 ;}
return grade;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter number of courses: ");
int n = input.nextInt();
String[] Courses = new String[n];
int sumOfcreadit=0;
int sumOfmarks =0;
for(int i =0; i<Courses.length;i++){
System.out.print("Enter a course code: ");
Courses[i] = input.next();
if(checkCourse(Courses,Courses[i])){
System.out.println("the course already registered");
i--;
}
System.out.print("Enter a credit: ");
int credit = input.nextInt();
System.out.print(" Enter a marks: ");
int marks = input.nextInt();
sumOfcreadit += credit;
sumOfmarks +=marks * credit;
}
double TotalMarks;
TotalMarks = sumOfmarks /sumOfcreadit;
System.out.println("The GPA is: "+gradeValue(TotalMarks));
}
I made some changes in your code and now it works. Changes are described in below code. There was 3 important changes.
I tried to make as less changes as possible to make your code work as expected
public static boolean checkCourse(String[] courseList, String code) {
boolean check = false;
for (int i = 0; i < courseList.length; i++) {
if (code.equals(courseList[i])) { // equals instead of == to compare strings
check = true;
break; // you have to break loop if it is true because else statement before returned false even if there was the same course code due to null values in next array elements which was not filled yet
}
}
return check;
}
public static double gradeValue(double marks) {
double grade = 1.0;
if (marks >= 95) {
grade = 5.0;
} else if (marks >= 90) {
grade = 4.75;
} else if (marks >= 85) {
grade = 4.5;
} else if (marks >= 80) {
grade = 4.0;
} else if (marks >= 75) {
grade = 3.5;
} else if (marks >= 70) {
grade = 3.0;
} else if (marks >= 65) {
grade = 2.5;
} else if (marks >= 60) {
grade = 2;
} else if (marks < 60) {
grade = 1;
}
return grade;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter number of courses: ");
int n = input.nextInt();
String[] Courses = new String[n];
int sumOfcreadit = 0;
int sumOfmarks = 0;
for (int i = 0; i < Courses.length; i++) {
System.out.print("Enter a course code: ");
String code = input.next();
if (checkCourse(Courses, code)){
System.out.println("the course already regestered ");
i--;
continue; // continue is neccessary to let user write value again if it already exists
}
Courses[i] = code;
System.out.print("Enter a credit: ");
int credit = input.nextInt();
System.out.print(" Enter a marks: ");
int marks = input.nextInt();
sumOfcreadit += credit;
sumOfmarks += marks * credit;
}
double TotalMarks;
TotalMarks = sumOfmarks / sumOfcreadit;
System.out.println("The GPA is: " + gradeValue(TotalMarks));
}
Use a set kind of structure to store all the course code visited, It will avoid unnecessary iteration on your course array
this method can be enhanced to
public static boolean checkCourse(HashSet<String> courses, String code){
boolean check = false;
if(courses.contains(code)){
check = true;
else
check = false;
}
return check;
}
Initialise the hashset courses and if the checkCourses method returns false add the course code in courses.
Initialize before loop like this
HashSet<String> courseSet = new HashSet<String>();
your if condition inside loop
if(checkCourse(courseSet,courses[i])){ // check for variable name , name should always start with lower case letter
System.out.println("the course already regestered ");
i--;
// You can use continue if you don't want processing for it
// it will skip the loop iteration and it will go next iteration
}else{
courseSet.add(courses[i]);
}

Char Input of Multiple Chars With Spaces in Between

I'm trying to make a grade class which determines one's chances of getting into college. The user should input something like: A B C D F E. The program should stop at E, as it is not a grade. The program also calculates GPA. In the Driver(included below), I call the print and the set functions, however, it simply does not exit the set loop.
Main Grades Class:
import java.util.*;
public class Grades {
//Declare instance variables here
private int numClass;
private double gpa;
public int count = 0;
public boolean gotF = false;
/**
* Method to get the grades and calculate the GPA
* This method also counts the number of classes taken
* and the number of Fs
*/
public void getGradesAndCalculateGPA()
{
//Your code goes here
Scanner stdin = new Scanner(System.in);
System.out.println("Enter a set of grades:");
do {
count += 1;
if(stdin.next().charAt(0) == 'A') {
gpa += 4.0;
//System.out.println("Grade Inputted");
}
else if(stdin.next().charAt(0) == 'B') {
gpa += 3.0;
//System.out.println("Grade Inputted");
}
else if(stdin.next().charAt(0) == 'C') {
gpa += 2.0;
//System.out.println("Grade Inputted");
}
else if(stdin.next().charAt(0) == 'D') {
gpa += 1.0;
//System.out.println("Grade Inputted");
}
else if(stdin.next().charAt(0) == 'F') {
gpa += 0.0;
gotF = true;
//System.out.println("Grade Inputted");
}
}while(stdin.next().charAt(0) == 'A' ||
stdin.next().charAt(0) == 'B' ||
stdin.next().charAt(0) == 'C' ||
stdin.next().charAt(0) == 'D' ||
stdin.next().charAt(0) == 'F');
gpa = gpa/count;
}
/**
* Method to print the appropriate message
*/
public void printMessage()
{
//Your code goes here
if(count < 4) {
System.out.printf("%7s %12d %30s", "", gpa, "Ineligible, taking less than four classes");
}
else if(gotF==true && gpa<2.0) {
System.out.printf("%7s %12d %30s", "", gpa, "Ineligible, gpa below 2.0 and has F grade");
}
else if(gotF == true) {
System.out.printf("%7s %12d %30s", "", gpa, "Ineligible, gpa above 2.0 but has F grade");
}
else if(gpa < 2.0) {
System.out.printf("%7s %12d %30s", "", gpa, "Ineligible, gpa below 2.0");
}
else {
System.out.printf("%7s %12d %8s", "", gpa, "Eligible");
}
}
}
Here is the driver class:
public class Driver {
public static void main(String[] args) {
Grades grader = new Grades();
grader.getGradesAndCalculateGPA();
grader.printMessage();
}
}
Each time you call stdin.next(), the Scanner waits until the user types something and hits enter. Your code is stacking up those statements with each if statement and is disrupting the programmatic flow. I fixed your code to only ask for the user input once per grade and store it in the grade variable for use in the if statements. I also added the validGrade boolean to break the loop when an invalid grade is entered.
Scanner stdin = new Scanner(System.in);
System.out.println("Enter a set of grades:");
boolean validGrade = true;
while (validGrade) {
count += 1;
char grade = stdin.next().charAt(0);
if (grade == 'A') {
gpa += 4.0;
System.out.println("Grade Inputted");
} else if (grade == 'B') {
gpa += 3.0;
System.out.println("Grade Inputted");
} else if (grade == 'C') {
gpa += 2.0;
System.out.println("Grade Inputted");
} else if (grade == 'D') {
gpa += 1.0;
System.out.println("Grade Inputted");
} else if (grade == 'F') {
gotF = true;
System.out.println("Grade Inputted");
} else {
validGrade = false;
}
}
gpa = gpa / count;
System.out.println("Your GPA is: " + gpa);

How to call same method multiple times to add something

So im creating a gpa calculator, it takes the 4 classes (or more if i want) and calculates the letter grade and gpa weight.
How would i use the same method 4 times and each time have it add the different inputted variables.
For example, the first input of the first calling (for the grade) is an 80.
if i call it again and input a 90, I want it to store the inital 80 and add the 90 and so on so i can calculate the gpa.
Here is my code
import java.util.*;
public class GpaCalculator{
public static void main(String[] args) {
{
System.out.println("Please enter your name>>>");
Scanner stringinputs = new Scanner(System.in);
String name = stringinputs.nextLine();
GreatGrader();
System.out.println();
System.out.println(name);
}
}
public static void GreatGrader(){
Scanner stringinput = new Scanner(System.in);
System.out.println("Please enter your course>>>");
String Course1 = stringinput.nextLine();
System.out.println("What is the weight of this class? Normal, Honors, or AP?>>>");
String weight = stringinput.nextLine();
System.out.println("What is your grade in the class?>>>");
String grade = stringinput.nextLine();
double gpa = 0;
if (weight.equalsIgnoreCase("honors"))
gpa = gpa + 1;
else if (weight.equalsIgnoreCase("Ap"))
gpa = gpa + 1.5;
else if (weight.equalsIgnoreCase("normal"));
String letter;
Scanner in = new Scanner(System.in);
int grades = in.nextInt();
if (grades >= 96)
{ gpa = 4.5;
letter = "A";}
else if (grades >= 92)
{ gpa = 4.0;
letter = "A";}
else if (grades >=88 )
{ gpa = 3.5;
letter = "B"; }
else if (grades >= 84 )
{ gpa = 3.0;
letter = "B";}
else if (grades >=76 )
{ gpa = 2.5;
letter = "C";}
else if (grades >= 72)
{gpa = 1.5;
letter = "C";}
else if (grades>=68)
{ gpa = 1.0;
letter = "D";}
else if (grades <=67)
{ gpa = 0;
letter = "F";
}
}
}

What am I doing wrong with this program?

I'm trying to write a code to convert a letter grade to a numerical value. I have this code but when I run it, I get an error saying java.lang.StringIndexOutOfBoundsException.
What am I doing wrong?
Here is the code:
import java.util.Scanner;
public class Lab6Smalls {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
String grade;
String letter1;
String letter2;
double gpa = 0;
System.out.print("Enter a letter grade: ");
grade = scan.nextLine();
letter1 = grade.substring(0,1);
letter2 = grade.substring(1,2);
if (letter1.equals("A") && letter2.equals("+")){
gpa = 4.3;
} else if (letter1.equals("A")){
gpa = 4.0;
} else if (letter1.equals("B")){
gpa = 3.0;
} else if (letter1.equals("C")){
gpa = 2.0;
} else if (letter1.equals("D")){
gpa = 1.0;
} else if (letter1.equals("F")){
gpa = 0.0;
} else {
System.out.println("The value is invalid.");
}
if (!letter1.equals("F")){
if(letter2.equals("+") && !letter1.equals("A")) gpa += 0.3;
else if(letter2.equals("-")) gpa -= 0.3;
}
System.out.println("The numerical value is " + gpa + ".");
}
}
There is an error because alphabets other than A+ do not have a second value
A+ has two letters
B has one so when you try to find a second, it breaks
C has one so when you try to find a second, it breaks
D has one so when you try to find a second, it breaks
You want to check if the second value exists, before you retrieve it.
Try this
String letter2 = "";
grade = scan.nextLine();
letter1 = grade.substring(0,1);
// Check, if there is a second letter, get it.
if (grade.length() >= 2) {
letter2 = grade.substring(1,2);
}
Before you substring(1, 2) you should make sure the length > 1.
The following is what you want.
import java.util.Scanner;
public class Lab6Smalls {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String grade;
double gpa;
System.out.print("Enter a letter grade: ");
grade = scan.nextLine();
if (null == grade || "".equals(grade)) {
System.out.println("The value is invalid.");
return;
}
switch (grade.substring(0, 1)) {
case "A":
gpa = 4.0;
break;
case "B":
gpa = 3.0;
break;
case "C":
gpa = 2.0;
break;
case "D":
gpa = 1.0;
break;
case "F":
gpa = 0.0;
break;
default:
System.out.println("The value is invalid. : " + grade);
return;
}
if (grade.length() > 1) {
String letter2 = grade.substring(1, 2);
if ("+".equals(letter2)) {
gpa += 0.3;
} else if ("-".equals(letter2)) {
gpa -= 0.3;
}
}
System.out.println("The numerical value is " + gpa + ".");
}
}

Not understanding how to make my for loop and if statement work

I have this, but I'm very lost in how I can get the final GPA to print out, I've tried various ways but have not been able to do it successfully. This is what I have:
Scanner input = new Scanner(System.in);
System.out.println("How many grades are you putting? ");
int length = input.nextInt();
input.nextLine();
String[] gradesArray = new String[length];
for(int i = 0; i < gradesArray.length; i++)
{
System.out.println("Enter grade (include + or -) ");
gradesArray[i] = input.nextLine();
double points = 0.0;
if(gradesArray[i].equalsIgnoreCase("A+") || gradesArray[i].equalsIgnoreCase("A"))
{
points += 4;
}
else if(gradesArray[i].equalsIgnoreCase("A-"))
{
points+= 3.7;
}
else if(gradesArray[i].equalsIgnoreCase("B+"))
{
points += 3.3;
}
else if(gradesArray[i].equalsIgnoreCase("B"))
{
points += 3.0;
}
else if(gradesArray[i].equalsIgnoreCase("B-"))
{
points += 2.7;
}
else if(gradesArray[i].equalsIgnoreCase("C+"))
{
points += 2.3;
}
else if(gradesArray[i].equalsIgnoreCase("C"))
{
points += 2.0;
}
else if(gradesArray[i].equalsIgnoreCase("D"))
{
points += 1.0;
}
else if(gradesArray[i].equalsIgnoreCase("F"))
{
points += 0.0;
}
else
{
System.out.println("Invalid grade");
}
System.out.println("GPA: " + points / gradesArray.length);
}
I'm guessing the GPA does not print out properly because after the condition matches the grade, it then goes right down to print, right? And also, how can I do it so if they enter an invalid grade, it makes the user start over.
You're very close. You need to add another bracket before your println to close out your forloop. You only want to calculate GPA once all of the grades are entered. So like this:
And, as Jason mentioned in the comments, you need to make sure to create points outside of the loop. Otherwise, you won't be able to access it afterwards to get calculate the full GPA.
double points = 0.0; //this has to go out here to be able to access it later
for(int i = 0; i < gradesArray.length; i++) {
System.out.println("Enter grade (include + or -) ");
gradesArray[i] = input.nextLine();
...
else if(gradesArray[i].equalsIgnoreCase("F")) {
points += 0.0;
} else {
System.out.println("Invalid grade");
}
}
System.out.println("GPA: " + points / gradesArray.length);
As for resetting input, this is easy as well. You can just use a while loop - so do something like this.
boolean inputNeeded = true;
while(inputNeeded) {
System.out.println("Please enter grades:);
String grade = scan.nextLine();
if(grade_is_valid_check_here) {
inputNeeded = false;
} else {
System.out.println("Input is invalid - please try again");
}
}
You could do something similar to this as well. You can use a switch block. points needs to be brought outside the loop or it will just get reset to 0.0 every time a user enters a grade.
To make the user start over if it is an invalid grade you could use a recursive call. This means after the the "Invalid grade" message you would call the method that starts the process over again. This would require a little more refactoring and separating some of this code into more methods.
Scanner input = new Scanner(System.in);
double points = 0.0;
System.out.println("How many grades are you putting? ");
int length = input.nextInt();
input.nextLine();
String[] gradesArray = new String[length];
for(int i = 0; i < gradesArray.length; i++){
System.out.println("Enter grade (include + or -) ");
gradesArray[i] = input.nextLine();
String grade = gradesArray[i].toUpperCase();
switch (gradesArray[i]) {
case "A+":
points += 4;
break;
case "A":
points += 4;
break;
case "A-":
points += 3.7;
break;
case "B+":
points += 3.3;
break;
default:
System.out.println("Invalid grade");
break;
}
}
System.out.println("GPA: " + points / gradesArray.length);
Aside from #Alex K's answer. Not sure if you have learned about HashMaps or not, but you could shorten your code down quite a bit by using them. It also makes it way easier to add another grade and point value with ease.
Scanner input = new Scanner(System. in );
System.out.println("How many grades are you putting? ");
int length = input.nextInt();
String[] gradesArray = new String[length];
//Create a HashMap with String as the key, and a Double as the value
Map < String, Double > grades = new HashMap < > ();
//Insert all the grades and point values
grades.put("A+", 4.0);
grades.put("A-", 3.7);
grades.put("B+", 3.3);
grades.put("B", 3.0);
grades.put("B-", 2.7);
grades.put("C+", 2.3);
grades.put("C", 2.0);
grades.put("D", 1.0);
grades.put("F", 0.0);
double points = 0.0;
for (int i = 0; i < gradesArray.length; i++) {
System.out.println("Enter grade (include + or -) ");
String grade = input.nextLine();
gradesArray[i] = grade;
//If the grades Map contains the inputted grade, use Map.get(grade) to obtain the value and add that to the points Double.
//Otherwise print invalid grade
if (grades.containsKey(grade)) {
points += grades.get(gradesArray[i]);
} else {
System.out.println("Invalid grade");
}
}
System.out.println("GPA: " + points / gradesArray.length);
All you need is declare points as a global variable and print out the GPA outside the for loop
public class Grade {
public static void main(String[] args){
double points=0.0;
Scanner input = new Scanner(System.in);
System.out.println("How many grades are you putting? ");
int length = input.nextInt();
input.nextLine();
String[] gradesArray = new String[length];
for(int i = 0; i < gradesArray.length; i++)
{
System.out.println("Enter grade (include + or -) ");
gradesArray[i] = input.nextLine();
if(gradesArray[i].equalsIgnoreCase("A+") || gradesArray[i].equalsIgnoreCase("A"))
{
points += 4;
}
else if(gradesArray[i].equalsIgnoreCase("A-"))
{
points+= 3.7;
}
else if(gradesArray[i].equalsIgnoreCase("B+"))
{
points += 3.3;
}
else if(gradesArray[i].equalsIgnoreCase("B"))
{
points += 3.0;
}
else if(gradesArray[i].equalsIgnoreCase("B-"))
{
points += 2.7;
}
else if(gradesArray[i].equalsIgnoreCase("C+"))
{
points += 2.3;
}
else if(gradesArray[i].equalsIgnoreCase("C"))
{
points += 2.0;
}
else if(gradesArray[i].equalsIgnoreCase("D"))
{
points += 1.0;
}
else if(gradesArray[i].equalsIgnoreCase("F"))
{
points += 0.0;
}
else
{
System.out.println("Invalid grade");
}
}
System.out.println("GPA: " + points / gradesArray.length);
}

Categories

Resources