I'm trying to make a class where you input any number of grades (A-F) and calculates the GPA and returns the GPA and eligibility to extracurricular activities. It seems like the scanner only allows one input, then prints the GPA and eligibility.
So far this is what I have:
import java.util.Scanner;
public class Grades
{
public static void main(String[] args)
{
double myGPA;
int myNumClasses;
double myValue;
Scanner sc = new Scanner(System.in);
System.out.println("Press any other lettter to calculate.");
System.out.print("Enter grades: ");
String input = sc.nextLine();
myValue = 0;
myNumClasses = 0;
myGPA = 0;
for (String next = sc.next(); input.equalsIgnoreCase("a") || input.equalsIgnoreCase("b") ||
input.equalsIgnoreCase("c")|| input.equalsIgnoreCase("d") || input.equalsIgnoreCase("f"); next = sc.next())
{
if (input.equalsIgnoreCase("a"))
{
myValue += 4.0;
myNumClasses += 1;
}
else if (input.equalsIgnoreCase("b"))
{
myValue += 3.0;
myNumClasses += 1;
}
else if (input.equalsIgnoreCase("c"))
{
myValue += 2.0;
myNumClasses += 1;
}
else if (input.equalsIgnoreCase("d"))
{
myValue += 1.0;
myNumClasses += 1;
}
else if (input.equalsIgnoreCase("f"))
{
myNumClasses += 1;
}
myGPA = myValue / myNumClasses;
if (myGPA >= 2.0 && myNumClasses >= 4)
{
System.out.println("Eligible");
}
else if (myNumClasses < 4)
{
System.out.println("Ineligible, taking less than 4 classes");
}
else if (myGPA >= 2.0 && input.equalsIgnoreCase("f"))
{
System.out.println("Ineligible, gpa above 2.0 but has F grade");
}
else if (myGPA <= 2.0 && input.equalsIgnoreCase("f"))
{
System.out.println("Ineligible, gpa below 2.0 and has F grade");
}
else if (myGPA < 2.0)
{
System.out.println("Inelligible, gpa below 2.0");
}
System.out.println("Your GPA = " + myGPA);
}
}
}
// It looks like your missing a for loop. I just copied some of your
//code and ran it through a for loop. The rest of the code is kind of unclear.
System.out.println("Enter the number of grades you will enter: ");
int userAns = sc.nextInt();
for (int index = 0; index <= userAns; index++)
{
System.out.println("Press any other letter to calculate.");
System.out.print("Enter grades: ");
String input = sc.nextLine();
}
Related
I just tried to get an integer value from the user for a variable in another a method that created differently from main but it gives an error message like this:
Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:941)
at java.base/java.util.Scanner.next(Scanner.java:1598)
at java.base/java.util.Scanner.nextInt(Scanner.java:2263)
at java.base/java.util.Scanner.nextInt(Scanner.java:2217)
at StoreUsingArrays_20210808043.menu(StoreUsingArrays_20210808043.java:14)
at StoreUsingArrays_20210808043.storeRun(StoreUsingArrays_20210808043.java:57)
at StoreUsingArrays_20210808043.main(StoreUsingArrays_20210808043.java:90)
Code:
import java.util.Arrays;
import java.util.Scanner;
public class StoreUsingArrays_20210808043 {
public static int menu(String[] items,double[] prices,int answer) {
Scanner input = new Scanner(System.in);
for (int i = 1;i <= items.length;i++) {
System.out.println(i+" - for "+items[i-1]+" ("+prices[i-1]+")");
}
System.out.println("0 - to checkout");
System.out.print("Please enter what would you like : ");
answer = input.nextInt();
System.out.println("Your choice was : "+answer);
input.close();
return answer;
}
public static void returnedAmounts(double amount) {
double bill200,bill100,bill50,bill20,bill10,bill5,bill1,coin50,coin25,coin10,coin1;
bill200 = (amount - (amount%200)) / 200;
amount = amount%200;
bill100 = (amount - (amount%100)) / 100;
amount = amount%100;
bill50 = (amount - (amount%50)) / 50;
amount = amount%50;
bill20 = (amount - (amount%20)) / 20;
amount = amount%20;
bill10 = (amount - (amount%10)) / 10;
amount = amount%10;
bill5 = (amount -(amount%5)) / 5;
amount = amount%5;
bill1 = (amount - (amount%1)) / 1;
amount = amount%1;
coin50 = (amount - (amount%0.50)) / 0.50;
amount = amount%0.50;
coin25 = (amount - (amount%0.25)) / 0.25;
amount = amount%0.25;
coin10 = (amount - (amount%0.10)) / 0.10;
amount = amount%0.10;
coin1 = (amount - (amount%0.01)) / 0.01;
double[] returnedNumbers = {bill200,bill100,bill50,bill20,bill10,bill5,bill1,coin50,coin25,coin10,coin1};
double[] returnedValues = {200,100,50,20,10,5,1,0.50,0.25,0.10,0.01};
for (int i = 0;i < returnedNumbers.length;i++) {
if ((returnedNumbers[i] > 0) && (returnedValues[i] > 0)) {
System.out.println((int)returnedNumbers[i]+" - "+returnedValues[i]);
}
}
}
public static void storeRun(String[] item,int[] quantity,double[] price) {
Scanner input = new Scanner(System.in);
capitalizeArray(item);
int choice,req = 0;
while (true) {
choice = menu(item, price, 0);
if (choice == 0) break;
else if (choice > item.length && choice < 0) {
System.out.println("ERROR:Invalid choice");
break;
}
else {
System.out.println("How many "+item[choice-1]+" would you like? ");
if (input.hasNextInt()) req = input.nextInt();
System.out.println(req);
}
}
input.close();
}
public static String capitalizeString(String text) {
return text.substring(0, 1).toUpperCase() + text.substring(1).toLowerCase();
}
public static String[] capitalizeArray(String[] name) {
for (int i = 0;i < name.length;i++) {
name[i] = capitalizeString(name[i]);
}
return name;
}
public static void main(String[] args) {
String[] item = {"bRead","cOLA","ROLL","BaKe"};
double[] price = {4,2,6,5};
int[] quantity = {10,25,17,22};
//capitalizeArray(item);
//System.out.println(Arrays.toString(item));
//menu(item, price, 0);
storeRun(item, quantity, price);
//returnedAmounts(167.5);
}
}
I expected to get a value for the req variable from user and use it for another purposes but I tried a lot of things like that:
Initializing the variable at the begin.
Removing the input.close() line.
(etc.)
But all of them didn't work.
Replace all input.close() by input.reset()
In method menu, replace answer = input.nextInt(); by if (input.hasNextInt()) answer = input.nextInt();
and it should work
I'm working on this project challenge called "Algebra Tutor" for my very first java class.
The program should be able to output a question to decide whether you want to solver for m or b or y in the formula y = mx + b.
Once one of those is pick by a number: "Select 1 to Solve for Y, 2 to Solve for M, 3 to Solve for B and 4 to quit. "
It should give you an output to solve the formula.
I'm working in part 3 of the project which is:
Update your program so that each problem type mode will repeatedly ask questions until the user gets 3 correct answers in a row.
If the attempts more than 3 questions in a particular mode, the program should provide a hint on how to solve problems of this type.
After the student has correctly answered 3 questions in a row, an overall score (the number of questions answered correctly divided by the total number of questions attempted) should be displayed, and the menu is presented again.
So I'm getting stuck on how I can place a counter that starts at 0 and every time the user answers correctly then 1 will be added to the counter and quit if it gets 3 in a row or go back to 0 if the user answer is incorrect.
I will provide my code I'm getting confused on how having a while loop inside of the if statement and then another while loop for the count, it's confusing I know but once you see my code you will see what I'm talking about.
So I know I can place a counter like this:
int counter = 0;
while (counter < 4)
if statement here
counter ++;
else
counter = 0;
import java.util.Scanner;
class AlgebraTutor {
public static void main(String[] arg) {
double min_value = -100;
double max_value = 100;
double m_value = generate_random(max_value, min_value);
double x_value = generate_random(max_value, min_value);
double b_value = generate_random(max_value, min_value);
double y_value = generate_random(max_value, min_value);
Scanner user_input = new Scanner(System.in);
int user_answer_int = 0;
while ((user_answer_int < 4) && (user_answer_int >= 0)) {
System.out.println("Select 1 to Solve for Y, 2 to Solve for M, 3 to Solve for B and 4 to quit. ");
user_answer_int = user_input.nextInt();
if (user_answer_int == 1) {
check_answer_for_y(m_value, x_value, b_value);
}
else if (user_answer_int == 2) {
check_answer_for_m(x_value, y_value, b_value);
}
else if (user_answer_int == 3) {
check_answer_for_b(m_value, x_value, y_value);
}
else {
System.out.println("You are done");
}
}
}
static void check_answer_for_m(double x_value, double y_value, double b_value) {
System.out.println("Solve For M Problem ");
System.out.println("Given: ");
System.out.println("b = " + b_value);
System.out.println("x = " + x_value);
System.out.println("y = " + y_value);
System.out.print("What is the value of m? ");
Scanner user_input = new Scanner(System.in);
String user_answer_m = "";
user_answer_m = user_input.next();
int user_answer_int = Integer.parseInt(user_answer_m);
int correct_answer_m = (((int)y_value - (int)b_value) / (int)x_value);
if (user_answer_int == correct_answer_m){
System.out.println("You are correct!");
} else {
System.out.print("Sorry, that is incorrect. ");
System.out.println("The answer is " + correct_answer_m);
}
}
static void check_answer_for_b(double m_value, double x_value, double y_value) {
System.out.println("Solve For B Problem ");
System.out.println("Given: ");
System.out.println("m = " + m_value);
System.out.println("x = " + x_value);
System.out.println("y = " + y_value);
System.out.print("What is the value of b? ");
Scanner user_input = new Scanner(System.in);
String user_answer_b = "";
user_answer_b = user_input.next();
int user_answer_int = Integer.parseInt(user_answer_b);
int correct_answer_b = ((int)y_value - ((int)m_value * (int)x_value));
if (user_answer_int == correct_answer_b){
System.out.println("You are correct!");
} else {
System.out.print("Sorry, that is incorrect. ");
System.out.println("The answer is " + correct_answer_b);
}
}
static void check_answer_for_y(double m_value, double x_value, double b_value) {
System.out.println("Solve For Y Problem ");
System.out.println("Given: ");
System.out.println("m = " + m_value);
System.out.println("x = " + x_value);
System.out.println("b = " + b_value);
System.out.print("What is the value of y? ");
Scanner user_input = new Scanner(System.in);
String user_answer_y = "";
user_answer_y = user_input.next();
int user_answer_int = Integer.parseInt(user_answer_y);
int correct_answer_y = (int) m_value * (int) x_value + (int) b_value;
if (user_answer_int == correct_answer_y) {
System.out.println("You are correct!");
} else {
System.out.print("Sorry, that is incorrect. ");
System.out.println("The answer is " + correct_answer_y);
}
}
static int generate_random(double max_value, double min_value) {
return (int) ((int) (Math.random() * ((max_value - min_value)+ 1)) + min_value);
}
}
Where I stated my while loop for the number entered by user
depending on the number then the if statement jumps in
where can I place my counter to start and catch all the if statements depending on the number the user picks and then if the user gets 3 correct in a row the program should go back to the main question. Can I do another while loop inside the one I already have? Or should I place it inside each if statement?
Place the loop here for each
else if (user_answer_int == 3) {
check_answer_for_b(m_value, x_value, y_value);
}
changing your main function to this.
public static void main(String[] arg) {
double min_value = -100;
double max_value = 100;
double m_value = generate_random(max_value, min_value);
double x_value = generate_random(max_value, min_value);
double b_value = generate_random(max_value, min_value);
double y_value = generate_random(max_value, min_value);
Scanner user_input = new Scanner(System.in);
int user_answer_int = 0;
while ((user_answer_int < 4) && (user_answer_int >= 0)) {
System.out.println("Select 1 to Solve for Y, 2 to Solve for M, 3 to Solve for B and 4 to quit. ");
user_answer_int = user_input.nextInt();
int i = 0;
if (user_answer_int == 1) {
while (i < 3){
if (check_answer_for_y(generate_random(max_value, min_value), generate_random(max_value, min_value), generate_random(max_value, min_value))) {
i++;
}
else {
i = 0;
}
}
}
else if (user_answer_int == 2) {
while (i < 3){
if (check_answer_for_m(generate_random(max_value, min_value), generate_random(max_value, min_value), generate_random(max_value, min_value))) {
i++;
}
else {
i = 0;
}
}
}
else if (user_answer_int == 3) {
while (i < 3){
if (check_answer_for_b(generate_random(max_value, min_value), generate_random(max_value, min_value), generate_random(max_value, min_value))) {
i++;
}
else {
i = 0;
}
}
}
else {
System.out.println("You are done");
}
}
}
static boolean check_answer_for_m(double x_value, double y_value, double b_value) {
System.out.println("Solve For M Problem ");
System.out.println("Given: ");
System.out.println("b = " + b_value);
System.out.println("x = " + x_value);
System.out.println("y = " + y_value);
System.out.print("What is the value of m? ");
Scanner user_input = new Scanner(System.in);
String user_answer_m = "";
user_answer_m = user_input.next();
int user_answer_int = Integer.parseInt(user_answer_m);
int correct_answer_m = (((int)y_value - (int)b_value) / (int)x_value);
if (user_answer_int == correct_answer_m){
System.out.println("You are correct!");
return true;
} else {
System.out.print("Sorry, that is incorrect. ");
System.out.println("The answer is " + correct_answer_m);
return false;
}
}
static boolean check_answer_for_b(double m_value, double x_value, double y_value) {
System.out.println("Solve For B Problem ");
System.out.println("Given: ");
System.out.println("m = " + m_value);
System.out.println("x = " + x_value);
System.out.println("y = " + y_value);
System.out.print("What is the value of b? ");
Scanner user_input = new Scanner(System.in);
String user_answer_b = "";
user_answer_b = user_input.next();
int user_answer_int = Integer.parseInt(user_answer_b);
int correct_answer_b = ((int)y_value - ((int)m_value * (int)x_value));
if (user_answer_int == correct_answer_b){
System.out.println("You are correct!");
return true;
} else {
System.out.print("Sorry, that is incorrect. ");
System.out.println("The answer is " + correct_answer_b);
return false;
}
}
static boolean check_answer_for_y(double m_value, double x_value, double b_value) {
System.out.println("Solve For Y Problem ");
System.out.println("Given: ");
System.out.println("m = " + m_value);
System.out.println("x = " + x_value);
System.out.println("b = " + b_value);
System.out.print("What is the value of y? ");
Scanner user_input = new Scanner(System.in);
String user_answer_y = "";
user_answer_y = user_input.next();
int user_answer_int = Integer.parseInt(user_answer_y);
int correct_answer_y = (int) m_value * (int) x_value + (int) b_value;
if (user_answer_int == correct_answer_y) {
System.out.println("You are correct!");
return true;
} else {
System.out.print("Sorry, that is incorrect. ");
System.out.println("The answer is " + correct_answer_y);
return false;
}
}
static int generate_random(double max_value, double min_value) {
return (int) ((int) (Math.random() * ((max_value - min_value)+ 1)) + min_value);
}
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]);
}
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
double score = 0, avg, sum = 0;
int index = 0, count = 0, num = 0;
readInput(keyboard, num);
double Test[] = new double[num];
System.out.print("\n");
while(count < Test.length)
{
System.out.printf("Enter your test score #%d:", count + 1);
try
{
score = keyboard.nextDouble();
}
catch(java.util.InputMismatchException e)
{
System.out.print("You have entered a non-numerical value, please try again\n");
keyboard.next();
continue;
}
if (score >= 0)
{
Test[count] = score;
sum = sum + score;
}
else
{
System.out.print("You have entered an invalid grade, please try again\n");
continue;
}
count++;
}
double maxValue = Test[0];
for (int i = 1; i < Test.length; i++)
{
if (Test[i] > maxValue)
{
maxValue = Test[i];
}
}
double minValue = Test[0];
for (int i = 1; i < Test.length; i++)
{
if (Test[i] < minValue)
{
minValue = Test[i];
index = i;
}
}
System.out.print("\nThe highest value is: " + maxValue + "\n");
System.out.print("The lowest value is: " + minValue + "\n");
avg = sum / Test.length;
System.out.printf("Your grade average is: %.1f \n\n", avg);
System.out.print("Would you like to drop the lowest grade: Y or N:");
char choice = keyboard.next().charAt(0);
if (choice == 'Y' || choice == 'y')
{
double newSum = sum - minValue;
double newAvg = newSum / (Test.length - 1);
System.out.print("\nYour old scores were: ");
System.out.print(Test[0]);
for (int i = 1; i < Test.length; i++)
{
System.out.print(", " + Test[i]);
}
System.out.print("\n\nYour new scores are: ");
for (int i = 0; i < Test.length; i++)
{
if (index != 0 && i != index)
{
if (i >= 1)
{
System.out.print(", ");
}
System.out.print(Test[i]);
}
else if (i != index)
{
if (i >= 2)
{
System.out.print(", ");
}
System.out.print(Test[i]);
}
}
System.out.printf("\n\nYour new average is: %.1f\n", newAvg);
}
else if (choice == 'N' || choice == 'n')
{
System.out.print("Your average has stayed the same.\n");
return;
}
else
{
System.out.print("You have entered an invalid response. Bye.\n");
return;
}
}
public static int readInput(Scanner keyboard, int num)
{
System.out.print("How many scores would you like to enter:");
try
{
num = keyboard.nextInt();
}
catch(java.util.InputMismatchException e)
{
System.out.print("You have entered a non-numerical value.\n");
readInput(keyboard, num);
}
if (num < 0)
{
System.out.print("You have entered a negative value.\n");
readInput(keyboard, num);
}
else if (num == 0)
{
System.out.print("If you have no test grades then you do not need this program.\n");
readInput(keyboard, num);
}
return num;
}
}
The program keeps failing and telling me I'm returning the value wrong. num needs to put into the array around line 10 but I'm having trouble getting the value to return. I need to protect against user input error which is why I'm using the Input Mismatch Exception but in order to return them to the beginning if they mess up I was told I needed to use a separate function. However, this sometimes results in an infinite loop of the function. If anyone can help with a new way of doing this or how to fix what I am currently doing that would be a huge help.
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);
}