Java GPA Program Issue - java

My program for some reason is calculating the GPA average wrong. If I enter 4.0 three times, then it says the average GPA is 3.0 but should be 4.0. Can someone help me find the issue?
//variables
double gpa = 0;
double total = 0;
int counter = 0;
int counter2 = 0;
do
{
String gpaEntry = JOptionPane.showInputDialog("Please enter GPAs:");
gpa = Double.parseDouble(gpaEntry);
if (gpa >= 3.5)
counter2 ++;
total += gpa;
counter ++;
}
while (gpa != 0);
double average = (double) (total/counter);
JOptionPane.showMessageDialog(null, "The Average GPA is: " + average);
JOptionPane.showMessageDialog(null, "Number of students:" + counter2);

Let's walk through the code
gpa = 0
get user input (user enters '2')
now gpa = 2
total += 2
counter ++
while(gpa != 0) // nope, gpa is 2
loop back
get user input (user enters '0')
now gpa = 0
total += 0
counter ++ // oops!
while(gpa != 0) // yep, quit the loop
but it's too late, we already incremented counter, so our average calculation is wrong

What is wrong is that if a user enters 0, then it runs the program and then exits.
Try this code (Sorry, I do not have an editor at the moment so you might have to fix some small thing).
//variables
double gpa = 0;
double total = 0;
int counter = 0;
int counter2 = 0;
String gpaEntry = JOptionPane.showInputDialog("Please enter GPAs:");
gpa = Double.parseDouble(gpaEntry);
while (gpa != 0) {
if (gpa >= 3.5)
counter2 ++;
total += gpa;
counter ++;
gpaEntry = JOptionPane.showInputDialog("Please enter GPAs:");
gpa = Double.parseDouble(gpaEntry);
}
JOptionPane.showMessageDialog(null, "The Average GPA is: " + average);
JOptionPane.showMessageDialog(null, "Number of students:" + counter2);
Comment if you have any more questions.

Related

Filling an array with doubles from user in a given range

So it's time to come back to the users of stackoverflow for help again on an assignment.
I'm supposed to fill an array with a size of 10 with doubles given from the user. The entered numbers are supposed to be grades so they have to be in the range of 0 - 100. Anything out of the range (more, less, or incorrect characters) are not saved to the array and the user is prompted to try again at the given index of the array. After either the array is filled to the max value or the user presses enter to skip, the program is supposed to return the grades entered in order and display the average.
public static final SIZE = 10;
Scanner userIn = new Scanner(System.in);
double[] grades = new double [SIZE];
int counter = 0;
int counterList = 1;
boolean exit = false;
String sTemp = "";
double gradeNum = 0;
double avrGrade = 0.0;
double sum = 0;
while((counter < SIZE) && (!exit)) {
System.out.println("Enter grade " + counterList +
", or press enter to quit.");
sTemp = userIn.nextLine();
counterList++;
if(sTemp.length() < 1) {
exit = true; //ending for loop
} else {
gradeNum = Double.parseDouble(sTemp);
grades[counter] = gradeNum;
counter++;
} //else statement
} //end of while loop
counterList = 1;
System.out.println("You entered " + counter + " grades total.");
for(int i = 0; i <= counter; i++) {
System.out.println("Your grade " + counterList + " is " + grades[i]);
counterList++;
}
for(int i = 0; i < grades.length; i++)
sum += grades[i];
System.out.println("The average grade is: " + sum / grades.length);
So I finished taking my user's input and calculating the average but I'm having trouble setting the range and not saving the invalid inputs. I also feel like once I started to struggle I got really sloppy and there might be stuff going on in there that's not needed. Let me know anything helps!
An example of what the program should output given different scenarios
You can trim down your code. There are variables that you don't require. Explanations after the code.
import java.util.Scanner;
public class GradeAvg {
private static final int SIZE = 10;
public static void main(String[] args) {
Scanner userIn = new Scanner(System.in);
double[] grades = new double [SIZE];
int counter = 0;
String sTemp = "";
double sum = 0;
while(counter < SIZE) {
System.out.println("Please enter grade " + (counter + 1) + ": ");
sTemp = userIn.nextLine();
if (sTemp.isEmpty()) {
break;
}
try {
grades[counter] = Double.parseDouble(sTemp);
}
catch (NumberFormatException xNumberFormat) {
System.out.println("That wasn't a valid percentage, I need a number between 0 - 100. Try again.");
continue;
}
if (grades[counter] < 0 || grades[counter] > 100) {
System.out.println("That wasn't a valid percentage, I need a number between 0 - 100. Try again.");
continue;
}
sum += grades[counter];
counter++;
} //end of while loop
for (int i = 0; i < counter; i++) {
System.out.println("grade " + (i + 1) + ": " + grades[i]);
}
System.out.println();
System.out.println("number of valid grades entered: " + counter);
System.out.println();
System.out.println("average: " + sum / counter);
}
}
After accepting the user input, first check if the user simply pressed <ENTER> without entering a value. I used method isEmpty(), of class java.lang.String, to do this check. If the user simply pressed <ENTER>, you need to exit the while loop. This is what break does. So no need for boolean variable exit.
Variable counter is all you need to both keep track of how many grades have been entered and which index of array grades needs to be assigned a value, so no need for variable counterList.
If an invalid value is entered, continue skips the rest of the while loop and starts a new loop iteration. Think of it as a sort of goto that jumps back to the statement:
while (counter < SIZE)
You can assign a value directly to an element in array grades so no need for variable gradeNum.
You can update variable sum inside the while loop so no need for the extra for loop in order to calculate the average. By the way, your calculation of the average is incorrect since you are dividing by the size of array grades and not by the actual number of grades that were entered. Adding up all the elements in array grades still gives you the correct sum since all elements of the array are implicitly initialized to 0 (zero).
I changed what the program displays on the screen so as to match your example of what the program should output given different scenarios.
Here is the output according to the sample you provided.
Please enter grade 1:
A
That wasn't a valid percentage, I need a number between 0 - 100. Try again.
Please enter grade 1:
100
Please enter grade 2:
Bob
That wasn't a valid percentage, I need a number between 0 - 100. Try again.
Please enter grade 2:
41.5
Please enter grade 3:
-7
That wasn't a valid percentage, I need a number between 0 - 100. Try again.
Please enter grade 3:
grade 1: 100.0
grade 2: 41.5
number of valid grades entered: 2
average: 70.75
I made some adjustments:
final int SIZE = 10;
Scanner userIn = new Scanner(System.in);
double[] grades = new double [SIZE];
int counter = 0;
String sTemp = "";
double gradeNum = 0;
double sum = 0;
while(counter < SIZE) {
boolean err = false;
System.out.println("Enter grade " + (counter + 1) +
", or press enter to quit.");
sTemp = userIn.nextLine();
try {
gradeNum = Double.parseDouble(sTemp);
} catch(NumberFormatException ex)
{
err = true;
}
if(sTemp.length() < 1) {
break; //ending the loop
} else if(gradeNum <= 100 && gradeNum >= 0 && !err)
{
grades[counter] = gradeNum;
counter++;
} else
{
System.out.println("That wasn't a valid percentage, I need a number between 0 - 100. Try again.");
}
} //end of while loop
userIn.close(); //closing the Scanner
System.out.println("You entered " + counter + " grades total.");
for(int i = 0; i < counter; i++) {
System.out.println("Your grade " + (i + 1)+ " is " + grades[i]);
}
for(int i = 0; i < counter; i++) {
sum += grades[i];
}
System.out.println("\nNumber of valid grades entered: " + counter + "\n");
System.out.println("The average grade is: " + sum / counter);
}
This seems to work, I made some corrections (like SIZE declaration, took out the println from the last loop, replaced exit with a break statement, ...). The most relevant changes are the input checks and the average grade calculation (I used counter instead of grades.length because it is always 10). The try/catch checks if the input string contains only numbers.
(sorry for bad english, just ask if something isn't clear)

Java-Number of scores needs to be one less in answer

So here is my code:
package e7;
import java.util.Scanner;
public class Q1 {
public static void main(String[] args)
{
double[] scores = new double[10];
double sum = 0.0D;
int count = 0;
Scanner sc = new Scanner(System.in);
do {
System.out.print("Enter a new score (-1 to end): ");
scores[count] = sc.nextDouble();
if (scores[count] >= 0.0D)
sum += scores[count];
}
while (scores[(count++)] >= 0.0D);
System.out.println("The total number of scores is: " + count );
double average = sum / (count - 1);
int numOfAbove = 0;
int numOfBelow = 0;
for (int i = 0; i < count - 1; i++) {
if (scores[i] >= average)
numOfAbove++;
else
numOfBelow++;
}
System.out.printf("Average is " + "%.2f\n",average);
System.out.println("Number of scores above or equal to the average " + numOfAbove);
System.out.println("Number of scores below the average " + numOfBelow);
}
}
How do make it display the correct number of scores calculated? If I input 2 numbers and then do the -1 one to end it keeps saying 3 scores. Should only be two. How do I fix this? Thanks
System.out.println("The total number of scores is: " + count );
You probably want:
System.out.println("The total number of scores is: " + (count - 1));
You could also change your loop from a do while to a while loop as follows,
while (true) {
System.out.print("Enter a new score (-1 to end): ");
double tempDouble = sc.nextDouble();
if (tempDouble >= 0.0D)
scores[count] = tempDouble;
sum += scores[count];
count++;
else
break;
}
That way as if your double input isn't correct it would break out of the while loop when the user entered -1. You might have to tweak it a bit for your use case.

How to replace a value in Java

So I am attempting to write a program where you enter your grades, totals them up, averages, and then drops the lowest grade. This is what I have so far, however, when I try to run the program I receive the average of 92 when I enter the values 100,100,75.
The average should be printing as 100. What is wrong with the code?
Thanks in advance!
import java.util.Scanner;
public class l3_drop_lowest_slide36 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double grade;
int count;
double minGrade;
double sumGrade;
double average;
System.out.println("Begin entering grades below. When done, type -1.");
System.out.println();
count = 0;
sumGrade = 0;
grade = 0;
minGrade = 100;
while ( grade != -1 ) {
sumGrade += grade;
count++;
System.out.print("Grade: ");
grade = input.nextDouble();
}
if ( grade < minGrade ) {
minGrade = grade;
}
if ( grade == -1 ) {
sumGrade = sumGrade - minGrade;
count = count - 1;
average = (sumGrade / count);
System.out.print("Your average is: " +average);
}
}
}
You can do something like this:
while ( grade != -1 ) {
sumGrade += grade;
count++;
System.out.print("Grade: ");
grade = input.nextDouble();
if(grade < minGrade && grade != -1)
minGrade = grade;
}
sumGrade = sumGrade - minGrade;
count = count - 1;
average = (sumGrade / count);
System.out.print("Your average is: " +average);
This way you are dropping out the minimum grade.
You are reading grade = input.nextDouble(); first and then checking if it's -1. Your while loop runs 4 times and not 3. So, essentially your count is 4 and not 3. Your minimum grade is -1 (the last input value) and not 75. Fix that logic and you should be good.
Your
if ( grade < minGrade ) {
minGrade = grade;
}
should be inside your
while ( grade != -1 ) {
}
Because when you get -1, -1 < 100 and minGrade = -1.
sumGrade - minGrade = (100+100+75) - (-1) = 276
And when u divide 276/3 = 92.

Java program calculates averages. How do I display highest average?

I have a java program that takes the scores of 4 players and computes each player's average score when -1 is inputted. At the end of the program I need to display the highest average score out of the 4 averages, however I cannot figure out how to do this, can you guys set me in the right direction? The program looks like this when it is run: (I have also attached my code) I cannot use anything but loops.
Player 1
Enter your score: 100
Enter your score: 90
Enter your score: 80
Enter your score: 70
Enter your score: -1 (when -1 is inputted, the average score is calculated)
Average Score = 85.00
Player 2
Enter your score: 90
Enter your score: 90
etc.
etc.
import java.util.Scanner;
public class BowlingScores
{
public static void main(String[]args)
{
double score = 0;
double totalScore = 0;
double count = 0;
Scanner input = new Scanner(System.in);
for (int player = 1; player <= 4; player++){
System.out.printf("\nPlayer %d\n", player);
do{
System.out.println("Enter Your Score: ");
totalScore = totalScore + score;
score = input.nextDouble();
count++;
} while (score != -1);
if (score == -1){
count--;
System.out.printf("Average Score = %.2f\n",totalScore/count);
count = 0;
score = 0;
totalScore = 0;
}
}
}
}
Just keep track of the highest average in another variable. Then in your score == -1 condition check to see if the current average is higher than the highest average, and if so make current the new highest. Then after your for loop you could print out the highest average.
You can add a copy of the highest at the top of your code like this double highest = 0 then in your for loop have a way to replace it if the current average is higher.
if(score > highest){
highest=score;
}
Then at the -1 you can either reset it to 0 or keep it going.
public static void main(String[] args) {
final List<Double> allAverages = new ArrayList<>();
double score = 0;
double totalScore = 0;
double avg = 0;
int count = -1;
Scanner input = new Scanner(System.in);
for (int player = 1; player <= 4; player++) {
System.out.printf("\nPlayer %d\n", player);
do {
System.out.println("Enter Your Score: ");
totalScore = totalScore + score;
score = input.nextDouble();
count++;
} while (score != -1);
avg = totalScore / count;
System.out.printf("Average Score = %.2f\n", avg);
allAverages.add(totalScore / count);
score = 0;
totalScore = 0;
count = -1;
}
System.out.println("The highest is : " + Collections.max(allAverages));
}
Here a list of the modifications I did to your code to get it working :
The variable count now start at -1, so there is no need to do count-- when we exit the loop.
I've added a List that keep a track of all the averages.
I've removed the validation if(count == -1) after the loop as the only way to exit the loop is to have count == -1 so we already know it is the actual value.
To retrieve the maximum of all averages, I use Collections.max(allAverages).
Take average of all 4 players and store into one array. Then check for the largest number in array.
double[] highest = new double[4];
for(int i=0; i<4; i++){
highest[i] = totalScore/count;
}
if(highest[0]>highest[1] && highest[0]>highest[2] && highest[0]>highest[3])
System.out.println("highest" + highest[0]);
else if(highest[1]>highest[0] && highest[1]>highest[2] && highest[0]>highest[3])
System.out.println("highest" + highest[1]);
else if(highest[2]>highest[0] && highest[2]>highest[1] && highest[0]>highest[3])
System.out.println("highest" + highest[2]);
else System.out.println("highest" + highest[3]);
public static void main(String[]args) {
double bestScore = 0;
int bestPlayer = 1;
Scanner input = new Scanner(System.in);
for (int player = 1; player <= 4; player++){
System.out.printf("\nPlayer %d\n", player);
int count = 0; // does not need to be double
double totalScore = 0;
do {
System.out.println("Enter Your Score: ");
double score = input.nextDouble();
if (score != -1) {
totalScore += score;
count++;
}
} while (score != -1);
double averageScore = totalScore / count;
if (averageScore > bestScore) {
bestScore = averageScore;
bestPlayer = player;
}
System.out.printf("Average Score = %.2f\n", averageScore);
}
System.out.printf("Best Average Score = %.2f, best player = %d\n", bestScore, bestPlayer);
}
Just keep a variable to record the top average score every time as in topAverage in my example below. The code is same as your's except I changed the variable names for my readability.
public static void main(String[] args) throws NumberFormatException,
IOException {
double currentScore = 0;
double totalScore = 0;
int numScores = 0;
double averageScore = 0;
double topAverage = 0;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
for (int i = 0; i < 4; i++) {
do {
System.out.println("Enter Score");
currentScore = Double.parseDouble(br.readLine());
totalScore = totalScore + currentScore;
numScores += 1;
} while (currentScore != -1);
numScores-=1;
totalScore+=1;
averageScore = totalScore / numScores;
System.out.println("Average Score is " + averageScore);
if (topAverage < averageScore) {
topAverage = averageScore;
}
currentScore = 0;
totalScore = 0;
numScores = 0;
}
System.out.println("Top Average is " + topAverage);
}
Edit
#Andrei Nikolaenko posted the same answer before me, so consider that answer, I am adding this edit because I want to mention that my browser did not refresh on time to show me that the answer has already been posted.

How do I find the lowest score entered using for loops [duplicate]

This question already has answers here:
Getting the lowest and highest value from integers without using arrays?
(2 answers)
Closed 9 years ago.
I need this code to print out the lowest score entered and I'm sitting here for hours and I can't figure out how to do it.I know how to make it using arrays but I need to use for loops.Do you have any hints?
Example output:
How many scores? 3
Enter score 1: 90
Enter score 2: 80
Enter score 3: 100
Lowest score is 80
My code:
int score,numScore,count;
Scanner keyboard = new Scanner(System.in);
System.out.print("How many scores? ");
numScore = keyboard.nextInt();
for(count = 1; count <= numScore; count++){
System.out.print("Enter score " + count + ":");
score = keyboard.nextInt();
}
Maintain a variable that you compare against with each keyboard input.
int lowestScore = 100000;
for(count = 1; count <= numScore; count++){
System.out.print("Enter score " + count + ":");
score = keyboard.nextInt();
if (score < lowestScore) {
lowestScore = score;
}
}
Maintain a variable to find the lowest score like this
int lower = -1;
Inside for loop
if(lower == -1) {
lower = score;
} else if(score < lower) {
lower = score;
}
Finally lower has the required value
Simply save the lowest score in a variable and update it every time the lower score is encountered:
int lowestScore = 100;
for(count = 1; count <= numScore; count++){
System.out.print("Enter score " + count + ":");
score = keyboard.nextInt();
if(score < lowestScore){
lowestScore = score;
}
}
Added 3 lines
int score,numScore,count;
int minimum;
Scanner keyboard = new Scanner(System.in);
System.out.print("How many scores? ");
numScore = keyboard.nextInt();
for(count = 1; count <= numScore; count++){
System.out.print("Enter score " + count + ":");
score = keyboard.nextInt();
if (count == 1) minimum = score;
if (score < minimum) minimum = score;
}

Categories