Current i am scanning in 4 exam score grades, each to their own variable that has been declared and initialized. I was wondering if there was better way i should be doing this to make it less clutters. Please bear with me though as i am currently in my first java class at uni and dont have any prior experience so i dont want the solution to be super complex, not yet at least but something easily understandable. Not sure if it helps/matters but i am using BlueJ as my IDE.
import java.util.*;
public class GradeCalculatorDriver
{
public static void main(String [] args){
String s1 = "student";//Declare student string variable;
String s2;
double exam1 = 0;//Declare and initalize variables.
double exam2 = 0;//Declare and initalize variables.
double exam3 = 0;//Declare and initalize variables.
double exam4 = 0;//Declare and initalize variables.
do{
Scanner input = new Scanner(System.in);
System.out.println("This program will calculate the average of 4 exam scores, and return the lowest, highest, and letter grade associated with the average");
System.out.println("Please enter the name of the student");//Request student name and scans it into a string.
String student = input.next();
System.out.println("Please enter one exam score, then hit enter and repeat for following grades.");//Request exam scores and scan them into variables.
exam1 = input.nextDouble();
exam2 = input.nextDouble();
exam3 = input.nextDouble();
exam4 = input.nextDouble();
double highest = GradeCalculator.high(exam1, exam2, exam3, exam4);//Calls highest grade method.
double lowest = GradeCalculator.low(exam1, exam2, exam3, exam4);//Calls lowest grade method.
double average = GradeCalculator.avg(exam1, exam2, exam3, exam4);//Calls average grade method.
char letterGrade = GradeCalculator.letter(exam1, exam2, exam3, exam4);//Calls letter grade method.
System.out.printf("The highest exam score is : %.2f " + highest);//Displays highest grade.
System.out.printf("The lowest exam score is : %.2f " + lowest);//Displays lowest grade.
System.out.printf("The average exam score is : %.2f " + average);//Displays average grade.
System.out.print("The letter grade is " + letterGrade);//Displays letter grade associated with average.
System.out.println("Would you like to enter another students grades? (yes/no)");//asks the user if they would like to calculate another factorial.
s2 = input.next();
} while (s2.equalsIgnoreCase("YES"));//checks to see what the users response was.
System.out.print("Thank you for using my program!");//Ending statement.
}
}
public class GradeCalculator{
public static double high(double exam1, double exam2, double exam3, double exam4){//Calculates the highest exam score entered.
double highest;//Declare and initilize variable.
highest = Math.max(Math.max(Math.max(exam1, exam2), exam3), exam4);
return highest;//Returns highest exam score.
}
public static double low(double exam1, double exam2, double exam3, double exam4){//Calculates the lowest exam score entered.
double lowest = 0;//Declare and initilize variable.
lowest = Math.min(Math.min(Math.min(exam1, exam2), exam3), exam4);
return lowest;//Returns highest exam score.
}
public static double avg (double exam1, double exam2, double exam3, double exam4){//Calculates the average exam score.
double average;//Declare variable.
double count = 4;//Declare and initilize variable.
average = ((exam1 + exam2 + exam3 + exam4) / count);
return average;//Returns average grade.
}
public static char letter (double exam1, double exam2, double exam3, double exam4){//Calculates the letterGrade based on the average exam score.
char letterGrade;//Declare and initilize variable.
double count = 4;//Declare and initilize variable.
double average = ((exam1 + exam2 + exam3 + exam4) / count);//declare and calculate average score.
if (average >= 90)
letterGrade = 'A';
else if (average >= 80)
letterGrade = 'B';
else if (average >= 70)
letterGrade = 'C';
else if (average >= 60)
letterGrade = 'D';
else
letterGrade = 'E';
return letterGrade;//Returns letter grade.
}
}
You can use a List<Double> scores = new ArrayList<>() to hold the exam score values and reduce code clutter. Then as you added new exam scores from user input, you would call scores.add(input.nextDouble()) for each input value.
Well, in my opinion, if this is your first kick at the cat (so to speak) then you're well on your way to being a successful Java programmer. As for reducing clutter, I suppose it depends upon what you have already learned, like the Java methods and statements already covered and are now at your disposal to create an application to accomplish the task at hand. There is really no way to know the extent of your learning and therefore the suggestions provided below should only be defined as mere suggestions:
There is nothing wrong with your current model other than a few minor errors which will generate a MissingFormatArgumentException and that is within the code lines:
System.out.printf("The highest exam score is : %.2f " + highest);
System.out.printf("The lowest exam score is : %.2f " + lowest);
System.out.printf("The average exam score is : %.2f " + average);
Any errors within your code should be repaired first. Each of the code lines above contains a fault and it's simply because there is no argument supplied for the format specifier (%.2f). This is because you placed a plus (+) character in place of where a comma separator character is to go so as to indicate the argument for %.2f to represent. In this case the + will append the following string or variable content to the string before it. The code should be:
System.out.printf("The highest exam score is : %.2f ", highest);
System.out.printf("The lowest exam score is : %.2f ", lowest);
System.out.printf("The average exam score is : %.2f ", average);
Or just utilize the String.format() method:
System.out.println("The lowest exam score is: " + String.format("%.2f",lowest));
System.out.println("The highest exam score is: " + String.format("%.2f", highest));
System.out.println("The average exam score is: " + String.format("%.2f", average));
Declaring Scanner should not be done upon every iteration of your do/while loop. Place this declaration above the do/while code block so as not to open unnecessary instances of Scanner.
Explaining application functionality does not need to be done upon each iteration of the do/while loop. Move this message above the do/while code block.
When prompting for User input don't use the Scanner#next() method unless you are expecting to receive string tokens. Sometimes it's just plain easier to use the Scanner#nextLine() method. In my opinion I feel it can give more flexibility and allows you a better opportunity to prevent possible exceptions (don't rely on exceptions if you can prevent them).
Believe it or not...sometimes comments can be the biggest source of code clutter. There is absolutely no need to comment the obvious. Yes, I might have done so but it's only so as to explain the code. It is expected to be deleted.
You can get rid of the code line: String s1 = "student";//Declare student string variable;. You don't seem to use this variable anywhere.
As already suggested an array or collection mechanism can be used to hold student scores however in the sense of reducing clutter, it won't for a mere 4 scores but it will for many more scores and therefore is a good way to handle this portion of the code. It is still a good way to go in any case if your course has already covered the use of Arrays and or ArrayLists. Not sure if your requirements are to utilize only what you've already learned. In any case....
To utilize an array to store Student scores you would also need to modify all your methods within the GradeCalculator Class. This in itself will remove parameter clutter since all you would need is a single parameter instead of 4 for each method. The methods in that class might look something like this if you want to use Arrays:
public class GradeCalculator {
public static double high(double[] exams) {//Calculates the highest exam score entered.
double highest = 0.0d;//Declare and initilize variable to 0.0
for (int i = 0; i < exams.length; i++) {
if (exams[i] > highest) {
highest = exams[i];
}
}
return highest;//Returns highest exam score.
}
public static double low(double[] exams) {//Calculates the lowest exam score entered.
double lowest = exams[0];
for (int i = 0; i < exams.length; i++) {
if (exams[i] < lowest) {
lowest = exams[i];
}
}
return lowest;//Returns lowest exam score.
}
public static double avg(double[] exams) {//Calculates the average exam score.
double average = 0.0d; //Declare variable.
double sum = 0.0d;
for (int i = 0; i < exams.length; i++) {
sum+= exams[i];
}
average = sum / exams.length;
return average; //Returns average grade.
}
//Calculates the letter-Grade based on the average exam score.
public static char letter(double average) {
char letterGrade;//Declare and initilize variable.
if (average >= 90) {
letterGrade = 'A';
}
else if (average >= 80) {
letterGrade = 'B';
}
else if (average >= 70) {
letterGrade = 'C';
}
else if (average >= 60) {
letterGrade = 'D';
}
else {
letterGrade = 'E';
}
return letterGrade; //Returns letter grade.
}
}
The letter() method only ever needed one parameter instead of the 4 you had forced to provide and that is the value that is returned from the average() method. You see, you don't need to calculate the average again within the letter() method since you already have a method that does, and has done that. Just pass the already calculated average to the letter() method.
To fill an array with User input it's best to carry out the task using a loop of some sort but then again, it depends upon exactly how you want the User to provide that information (like Test Scores). Perhaps you would like the User to supply all the scores from a single input by separating each score with a white-space:
Please enter all student scores (separated with a space):
65 112 75 88
The code for this might look something like this:
String s2;
boolean invalidEntry;
String LS = System.lineSeparator();
double[] exams; // Declare Array
Scanner input = new Scanner(System.in);
System.out.println("This program will calculate the average of any number of "
+ LS + "desired exam scores and return the lowest, highest, and "
+ LS + "letter grade associated with that determined average." + LS);
do {
s2 = "";
invalidEntry = false;
// Request Student Name
System.out.println("Please enter the name of the student (nothing to exit):");
String student = input.nextLine();
if (student.equals("")) { break; }
// Request exam scores
System.out.println("Please enter all student scores (each separated with a space): ");
String scores = input.nextLine();
// If nothing was supplied break out of loop
if (scores.equals("")) {
invalidEntry = true;
break;
}
String[] scoresArray = scores.split("\\s+"); // Split the input into single scores (regex "\\s+" is used to split on one or more whitespaces).
exams = new double[scoresArray.length]; // Initalize Array.
// Convert scores to double data type...
for (int i = 0; i < scoresArray.length; i++) {
/* Is the string value actually a numerical signed
or unsigned integer or double type value. Save
this Regular Expression. It's handy to have. */
if (scoresArray[i].matches("-?\\d+(\\.\\d+)?")) {
exams[i] = Double.parseDouble(scoresArray[i]);
}
else {
System.out.println("One or more of the Scores supplied are invalid! "
+ "Enter Student Scores again!" + LS);
invalidEntry = true;
break;
}
}
if (invalidEntry) { continue; } // Redo loop on Invalid Entry
double highest = high(exams);
double lowest = low(exams);
double average = avg(exams);
char letterGrade = letter(average);
System.out.println(LS + "Results For Student: " + student);
System.out.println("From " + String.format("%02d" , exams.length) +
" exam scores: " +
Arrays.toString(exams).replaceAll("[\\[\\]]", ""));
System.out.println("The lowest exam score is: " + String.format("%.2f",lowest));
System.out.println("The highest exam score is: " + String.format("%.2f", highest));
System.out.println("The average exam score is: " + String.format("%.2f", average));
System.out.println("The letter grade is: " + letterGrade + LS);
while (s2.equals("")) {
System.out.println("Would you like to enter another Students Scores? (yes/no)");
s2 = input.nextLine();
if (!s2.equalsIgnoreCase("yes") && !s2.equalsIgnoreCase("no")) {
System.out.println("Invalid Response! 'Yes' or 'No' only!");
s2 = "";
}
}
} while (s2.equalsIgnoreCase("yes") || invalidEntry);
System.out.println("Thank you for using my program!");
Sometimes it is just easier for the User to enter all the scores on one line as demonstrated within the above code however, you set the rules towards how your application is to function. If you want each score to be entered individually then so be it. The code might then look something like this:
String s2;
int indexCounter; // Declare an index counter for array.
boolean invalidEntry;
String LS = System.lineSeparator();
double[] exams; //Declare Array.
Scanner input = new Scanner(System.in);
System.out.println("This program will calculate the average of any number of "
+ LS + "desired exam scores and return the lowest, highest, and "
+ LS + "letter grade associated with that determined average." + LS);
do {
s2 = "";
indexCounter = 0; // Set index counter to 0
invalidEntry = false;
// Request Student Name
System.out.println("Please enter the name of the Student (nothing to exit):");
String student = input.nextLine();
if (student.equals("")) { break; }
// Get number of Scores to enter from User
int numberOfScores = 0;
while (numberOfScores == 0) {
System.out.println("Please enter the number of scores you wish to enter:");
String numScores = input.nextLine();
// Is the value supplied a String Integer value
if (!numScores.matches("\\d+")) {
System.out.println("Invalid number of scores provided! Try Again..." + LS);
continue;
}
numberOfScores = Integer.parseInt(numScores);
}
exams = new double[numberOfScores]; // Initialize Array
// Request exam scores
while (indexCounter < numberOfScores) {
System.out.println("Please enter exam score #" + (indexCounter + 1) +
" then hit enter: ");
exams[indexCounter] = input.nextDouble();
input.nextLine(); // Clear the scanner buffer
indexCounter++;
}
double highest = high(exams);
double lowest = low(exams);
double average = avg(exams);
char letterGrade = letter(average);
System.out.println(LS + "Results For Student: " + student);
System.out.println("From " + String.format("%02d" , exams.length) +
" exam scores: " +
Arrays.toString(exams).replaceAll("[\\[\\]]", ""));
System.out.println("The lowest exam score is: " + String.format("%.2f",lowest));
System.out.println("The highest exam score is: " + String.format("%.2f", highest));
System.out.println("The average exam score is: " + String.format("%.2f", average));
System.out.println("The letter grade is: " + letterGrade + LS);
while (s2.equals("")) {
System.out.println("Would you like to enter another Student's Scores? (yes/no)");
s2 = input.nextLine();
if (!s2.equalsIgnoreCase("YES") && !s2.equalsIgnoreCase("NO")) {
System.out.println("Invalid Response! 'Yes' or 'No' only!");
s2 = "";
}
}
} while (s2.equalsIgnoreCase("YES") || invalidEntry);
System.out.println("Thank you for using my program!");
You will have noticed that some of the code above takes advantage of Regular Expressions such as "\\s+", "\\d+", "[\\[\\]]", or even "-?\\d+(\\.\\d+)?". It's never to late to learn how to utilize Java's java.util.regex package for pattern matching. It can quickly become a close friend for you and once learned, you will find yourself using it all the time. To test Regular Expressions and to get explanations of what a particular expression does you can use the website RegEx101.com for example: this regex.
Related
I'm currently working on code that asks the users for their grades in a loop then outputs the highest, lowest, average, etc.
I'm having a bit of trouble figuring out how to show a letter grade next to their valid number grade. For example: 79 (C+).
If anyone can point me in the right direction what I need to do that'd be great.
import java.util.*;
public class Main {
public static void main(String[] args) {
/*
I know the code isn't the most efficient but im still learning how to use more methods so please
bear with me for the beginning of the semester for the time being.
*/
ArrayList<Double> invalidnums = new ArrayList<>();
ArrayList<Double> validnums = new ArrayList<>();
Scanner scan = new Scanner(System.in);
double totalinvalidGrade=0, totalvalidGrade=0;
double sum = 0;
//INPUT OF THE GRADES THROUGH THE ARRAYLIST
while (true) {
System.out.println("Enter a grade: ");
double grade = scan.nextInt();
if (grade <= (-2)) {
invalidnums.add(grade);
totalinvalidGrade++;
System.out.println("Error, Grade must be between (0-100); or -1 to finish");
} else if (grade >= 101) {
invalidnums.add(grade);
totalinvalidGrade++;
System.out.println("Error, Grade must be between (0-100); or -1 to finish");
}
else {
validnums.add(grade);
totalvalidGrade++;
}
if (grade == -1) {
break;
}
}
//Start of the GRADES SUMMARY:
//PRINTS THE AMOUNT OF VALID AND INVALID GRADES POSTED.
System.out.println("You submitted " +totalinvalidGrade+ " invalid grades");
System.out.println("You submitted " +totalvalidGrade+ " valid grades");
//PRINTS THE HIGHEST AND LOWEST GRADES ALONG WITH THE AVERAGE.
System.out.println("Highest Grade: "+Collections.max(validnums));
System.out.println("Lowest Grade: "+Collections.min(invalidnums));
for (double value : validnums) {
sum += value;
}
//return sum;
System.out.println("Average: "+sum);
//PRINTS THE LIST OF VALID AND INVALID GRADES:
System.out.println("Here are the "+totalvalidGrade+" valid grades: ");
for (Double valelement : validnums) {
System.out.println(valelement);
}
System.out.println("Here are the "+totalinvalidGrade+" invalid grades: ");
for (Double element : invalidnums) {
System.out.println(element);
}
}
}
//EOC
//SOURCES I USED TO HELP DEVELOP MY CODE AND UNDERSTAND:
//MAX AND MIN GRADES: https://www.tutorialspoint.com/find-maximum-element-of-arraylist-with-java-collections
//
I am creating a program that takes in employee payroll information and then displays the average and total afterwards. Everything seems to be working correctly except for the fact I cannot get the program to end when I enter the sentinel value of -1 for the hours worked so that the program can display the total and average of the employees. Any help is greatly appreciated.
import java.util.Scanner;
public class PayrollDo
{
public static void main(String[] args)
{
int hoursWorked = 0;
int grossPay = 0;
int empCounter = 0;
int total = 0;
Scanner keyboard = new Scanner(System.in);
do {
total = total + grossPay; // add gross to total
empCounter = empCounter + 1; // incriment counter
System.out.print("Enter hours worked: ");
hoursWorked = keyboard.nextInt();
System.out.print("Enter hourly wage: ");
int hourlyWage = keyboard.nextInt();
//System.out.println("Grosspay is " + (hourlyWage * hoursWorked));
keyboard.nextLine();
System.out.println("Enter employee name ");
String name = keyboard.nextLine();
} while(hoursWorked != -1);
// if user entered at least one employee
if (empCounter != 0) {
// use number with decimal point to calculate average of employees
int average = (int) total / empCounter;
// display total and average (with two digits of precision)
System.out.printf("%nTotal of the %d employees entered is %d%n",
empCounter, total);
System.out.printf("Employee average is " + average);
}
else {
// no employees were entered, so output appropriate message
System.out.println("No employees were entered");
}
}
}
Test soon after entering the value whether it is -1 or not
System.out.print("Enter hours worked: ");
hoursWorked = keyboard.nextInt();
if (hoursWorked == -1) break;
edit
I think you will also have trouble with Integer division http://stackoverflow.com/questions/4685450/why-is-the-result-of-1-3-0
You could restructure your do loop to put the hoursWorked input last (otherwise you have to complete the entries) - and also, add a conditional to reject all entries that cycle, otherwise empCounter is off by one. And I think the total calculation needs reworking too:
do {
System.out.println("Enter employee name ");
String name = keyboard.nextLine();
System.out.print("Enter hourly wage: ");
int hourlyWage = keyboard.nextInt();
System.out.print("Enter hours worked: ");
hoursWorked = keyboard.nextInt();
keyboard.nextLine();
if (hoursWorked != -1) {
total = total + (hourlyWage * hoursWorked); //
empCounter = empCounter + 1; // incriment counter
}
} while(hoursWorked != -1);
In cases like this it can be simpler to have a question like "More Employees? (y/n)" that is used to terminate the loop, using a boolean flag as the while terminator.
I do not understand how the for loop works and what it is doing. The code is for a project that averages a users test scores and is based on how many test scores he wants to input.
I know that the program is returning as many inputs the user asks but I do not know how the for loop is doing that. I am trying to understand how it operates and what it is doing.
import java.util.Scanner;
public class average
{
public static String getLetterGrade(double average) {
if (average < 60) {
return "F";
} else if (average < 70) {
return "D";
} else if (average < 80) {
return "C";
} else if (average < 90){
return "B";
}
else;{
return "A";
}
}
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("Welcome, please type your first name. ");
String name = scan.nextLine();
System.out.println("Welcome, please type your last name. ");
String last = scan.nextLine();
int n;
System.out.println("How many tests would you like the average of?");
n = scan.nextInt();
while(n<0)
{
System.out.println("Invalid input.");
System.out.println("How many tests would you like the average
of?");
n = scan.nextInt();
}
double sum = 0, grade;
System.out.println("Enter " + n + " scores.");
for(int i = 0;i<n;i++)
{
grade = scan.nextDouble();
sum += grade;
}
double average = (sum/n);
System.out.println("Okay " + name.charAt(0) + last.charAt(0) + ", Your
average score is " + (average));
System.out.println("Your letter grade is " + getLetterGrade(average));
}
}
The program runs normally and does not have errors. I am trying to understand how the for loop is working.
the for loop is trying to get the numbers(scores) which we want to calculate average on them.
for loop runs for n times which is the number of inputs (user gives this number as input).
in its body, it calls scan.nextDouble to get the nex number from the console. then adds this number to sum.
I'm writing a program where a user enters a number of students in a class, the number of exams taken in the class, then enters each student's names and exam scores. The program then calculates that student's grade and assigns them a corresponding letter grade. Then finally, it adds their scores to a classSum, calculates the average class score and displays it.
This is what I have so far:
public class GradeCalculator {
public static void main(String[] args) {
int classSum = 0; // variable used to hold sum of entire classes exams
int classExams = 0; // variable used to hold number of exams taken by whole class
Scanner s = new Scanner(System.in);
System.out.println("Welcome to Gradecalculator!");
System.out.println("Please enter the number of students:");
int students = s.nextInt();
System.out.println("Please enter the number of exams:");
int exams = s.nextInt();
int i = 0;
int studentnumber = 1;
int sum = 0;
while (i < students) { // loop until it matches number of students entered above
i++;
sum = 0;
System.out.println("Enter student " + studentnumber++ + "'s name :");
String studentname = s.next();
System.out.println("Enter exam scores :");
int input = 0;
for (; input < exams; input++) {
int n = s.nextInt();
sum+=n;
if (n < 0) {
System.out.println("Invalid exam scores, reenter: "); //if one of the scores entered is negative, display message
}
}
double average = sum/exams; // assign letter grade based on average of exams
if (average <= 100 && average >= 90) {
System.out.println("Letter grade: A");
System.out.println(studentname + " gets 4 stars! ****");
} if (average <= 89 && average >= 80) {
System.out.println("Letter grade: B");
System.out.println(studentname + " gets 3 stars! ***");
} if (average <= 79 && average >= 70) {
System.out.println("Letter grade: C");
System.out.println(studentname + " gets 2 stars! **");
} if (average <= 69 && average >= 60) {
System.out.println("Letter grade: D");
System.out.println(studentname + " gets 1 star! *");
} if (average <= 59) {
System.out.println("Letter grade: F");
System.out.println(studentname + " gets 0 stars!");
}
classSum += sum; // add sum of this student's scores to the classSum
classExams += exams; // add exams taken by this student to amount of exams taken by whole class
}
int classAverage = classSum/classExams; // compute class average
System.out.println("Class statistics:");
System.out.println("\tAverage: " + classAverage);
}
}
And this is the output I get:
Welcome to Gradecalculator!
Please enter the number of students:
2
Please enter the number of exams:
3
Enter student 1's name :
sam
Enter exam scores :
80 80 80
Letter grade: B
sam gets 3 stars! ***
Enter student 2's name :
joe
Enter exam scores :
90 90 90
Class statistics:
Average: 125
As you can see, after the first student, entering the name and exam scores does not display the next student's letter grade as the loop is supposed to do. Also, the class average is not being calculated correctly. I'm at a bit of a loss here with where I'm going wrong.
You have to set sum to 0 each turn of the loop
while (i < students) { // loop until it matches number of students entered above
i++;
sum = 0;
System.out.println("Enter student " + studentnumber++ + "'s name :"); String studentname = s.next();
// [...]
You do not reset (assign zero to) sum inside the loop. This means that after Sam, when it's Joe's turn, his scores get added on top of sam's! For this reason, you have to reset sum before the score reading and adding loop.
This is also why it didn't print anything about Joe. Since you basically have the sum of the scores of six exams divided by only three, you get a result that's more than a hundred, and that is not covered by any of your if statements.
I have an assignment for class that requires us to take input from the user, drop the lowest assignment grade, then take a few more grades, calculate the average. I've got all that done but the last step is we must ask the user if they want to repeat the program for another student. The do while loop I have won't execute.
import java.util.Scanner;
public class CalculateGrades{
public static void main(String [] args){
Scanner sc = new Scanner (System.in);
double score;
double sum=0;
double lowest=100;
do{
//ASSIGNMENT GRADES
for(int i=1;i<=5;i++){
System.out.println("enter grade for assignment " +i);
score=sc.nextDouble();
sum=sum+score;
if(score<lowest){
lowest=score;
}
}
sum=sum-lowest;
double assignmentAvg= sum/4;
System.out.println("After the lowest grade is dropped, your assignment average is " + assignmentAvg);
//EXAM GRADES
System.out.println("enter grade for exam one");
double exam1=sc.nextDouble();
System.out.println("enter grade for exam two");
double exam2=sc.nextDouble();
//LAB GRADE
System.out.println("enter grade for lab");
double lab= sc.nextDouble();
//FINAL EXAM GRADE
System.out.println("enter grade for final exam");
double Final=sc.nextDouble();
//AVERAGE
double avg= (assignmentAvg*.2)+(exam1*.15)+(exam2*.2)+(lab*.2)+(Final*.25);
if(avg >=90){
System.out.println("Your weighted average is " + avg + " and your letter grade is A");
}
else if(avg >=80){
System.out.println("Your weighted average is " + avg + " and your letter grade is B");
}
else if(avg >=70){
System.out.println("Your weighted average is " + avg + " and your letter grade is C");
}
else if(avg >=60){
System.out.println("Your weighted average is " + avg + " and your letter grade is D");
}
else{
System.out.println("Your weighted average is " + avg + " and your letter grade is F");
}
System.out.println("Would you like to calculate for another student? Press 1 for yes, or any key to terminate");
int again= sc.nextInt();
}while(again==1);
// for next student reset sum
}
}
Your again variable is out of scope. Check this. Fix is to declare again before the loop.