GPA calculator assistance - java

Hi I was wondering if I could get some help with a GPA calculator.
What it needs to do is:
The input will consist of a sequence of terms, e.g., semesters.
The input for each term will consist of grades and credits for courses taken within that term.
For each term, the user will type in an integer that represents the number of courses
taken within that term.
Each course is specified by a String letter grade and an int number of credits, in that order, separated by white space. 5. If the user types in -1 for the number of courses taken in a term, then the program must print a final overall summary and then terminate.
DO NOT prompt for any input. Thus, after you run your program in BlueJ, type Ctrl-T to force the Terminal window to pop up.
As always, follow the input / output format depicted in the Sample runs section.
Shown below is the error message I get and the code I have, thank you for any assistance in advance or tips I could try.
Terminal window and error message:
import java.util.Scanner;
/*
*
*
*/
public class Prog2 {
public static void main(String args[]) {
Scanner numberInput = new Scanner(System.in);
int numberofClasses = numberInput.nextInt();
Scanner input = new Scanner(System.in);
String [] grade = new String[5];
int [] credit = new int [5];
double totalCredit = 0.0;
double realGrade = 0.0;
double result = 0.0;
while (numberofClasses > 0)
{
for (int x = 0; x < numberofClasses; x++ )
{
grade[x] = input.next();
credit[x] = input.nextInt();
}
for(int x=0;x < numberofClasses; x++ ){
if(grade[x].equals("A+")){
realGrade=4.0;
}
else if(grade[x].equals("A")){
realGrade=4.0;
}
else if(grade[x].equals("A-")){
realGrade=3.67;
}
else if(grade[x].equals("B+")){
realGrade=3.33;
}
else if(grade[x].equals("B")){
realGrade=3.00;
}
else if(grade[x].equals("B-")){
realGrade=2.67;
}
else if(grade[x].equals("C+")){
realGrade=2.33;
}
else if(grade[x].equals("C")){
realGrade=2.00;
}
else if(grade[x].equals("C-")){
realGrade=1.33;
}
result = result+realGrade*credit[x];
totalCredit=totalCredit+credit[x];
}
System.out.println("Summary for term:");
System.out.println("----------------------------------");
System.out.println("Term total grade points: " + result);
System.out.println("Term total credits:" + totalCredit);
System.out.println("GPA:"+result/totalCredit);
}
// This block is getting used later please ignore
System.out.println("Final Summary:");
System.out.println("----------------------------------");
System.out.println(" Overall terms");
System.out.println(" Total grade points: " + result);// this needs to be all );
System.out.println(" Total credits" + totalCredit);//This needs to be all );
System.out.println("Cumulative GPA:"+result/totalCredit);
}
}

When your while loop ends, numberofClasses still contains the value that was entered before the while loop started the first time. Specifically, after you output the line:
GPA=3.0588...
you hit the end of the loop, then return to:
while (numberofClasses > 0)
which is true. The next "3" that you enter doesn't go into numberofClasses, it is picked up by
grade[x] = input.next();
Then the "A" is picked up by
credit[x] = input.nextInt();
which throws an exception since it's not an integer.
All you need to do is ask for the number of classes again at the end of the while loop:
System.out.println("GPA:"+result/totalCredit);
numberofClasses = numberInput.nextInt();
}
Output:
5
A 3
B 2
C 4
A 5
C 3
Summary for term:
----------------------------------
Term total grade points: 52.0
Term total credits:17.0
GPA:3.0588235294117645
3
A 3
B 5
C 1
Summary for term:
----------------------------------
Term total grade points: 81.0
Term total credits:26.0
GPA:3.1153846153846154

i recommend looking into whether your compiler or IDE has a "debug" feature. It is a very helpful tool, and lets you watch how your program goes through your code
Just a tip...
When you ask for input, print what you're asking for first. When I launched your program I had no idea what to do. Try adding System.out.println("input number of classes you took");before you prompt for that number.
Here is what is wrong. (If you printed what you're asking for first, this would be more apparent).
after your program displays the stats, you enter 5. Yet your program is actually still on this line grade[x] = input.next(); on line 22 i believe.
when you enter 5, your scanner is expecting a letter. and an exception is thrown.
you need to consider how you escape this loop here. while (numberofClasses > 0) perhaps use an if statement? otherwise your program loops for forever, never asking for a new class number

Related

Adding message when certain condition is met (Java)

Total newbie here, please forgive the silly question. As an exercise I had to make a program (using do and while loops) that calculates the average of the numbers typed in and exits when the user types 0. I figured the first part out :) The second part of the exercise is to change the program to display an error message if users types 0 before typing any other number. Can you kindly explain to me what is the easiest way to accomplish this? If you provide the code is great but I’d also like an explanation so I am actually understanding what I need to do.
Thank you! Here is the code:
import java.util.Scanner;
public class totalave1 {
public static void main(String[] args) {
int number, average, total = 0, counter = 0;
Scanner fromKeyboard = new Scanner(System.in);
do {
System.out.println("Enter number to calculate the average, or 0 to exit");
number = fromKeyboard.nextInt();
total = total + number;
counter = counter + 1;
average = (total) / counter;
} while (number != 0);
System.out.println("The average of all numbers entered is: " + average);
}
}
The second part of the exercise is to change the program to display
an error message if users types 0 before typing any other number.
It is not very clear :
Do you you need to display a error message and the program stops ?
Do you you need to display a error message and to force the input to start again ?
In the first case, just add a condition after this instruction : number=fromKeyboard.nextInt(); :
do{
System.out.println("Enter number to calculate the average, or 0 to exit");
number=fromKeyboard.nextInt();
if (number == 0 && counter == 0){
System.out.println("Must not start by zero");
return;
}
...
} while (number!=0);
In the second case you could pass to the next iteration to take a new input.
To allow to go to next iteration, just change the number from zero to any value different from zero in order that the while condition is true.
do{
System.out.println("Enter number to calculate the average, or 0 to exit");
number=fromKeyboard.nextInt();
if (number == 0 && counter == 0){
System.out.println("Must not start by zero");
number = 1;
continue;
}
...
} while (number!=0);
The good news is that you probably have done the hardest part. :) However, I don't want to give too much away, so...
Have you learned about control flow? I assume you might have a little bit, as you are using do and while. I would suggest taking a look at the following Java documentation first: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/if.html
Then, look at your current solution and try to think what conditions you have that would lead you to display the error message, using if statements. How do you know the user typed a 0? How do you know it's the first thing they entered? Are there any variables that you have now that can help you, or do you need to create a new one?
I know this is not a code answer, but you did well in this first part by yourself already. Let us know if you need further hand.
Don't go down code after reading and if you cant then see the code.
First you have to learn about the flow control. Second you have to check whether user entered 0 after few numbers get entered or not, for that you have to some if condition. If current number if 0 and it is entered before anyother number then you have to leave rest of the code inside loop and continue to next iteration.
import java.util.Scanner;
public class totalave1
{
public static void main (String[]args)
{
int number, average, total=0, counter=0;
boolean firstTime = true;
Scanner fromKeyboard=new Scanner (System.in);
do{
System.out.println("Enter number to calculate the average, or 0 to exit");
number=fromKeyboard.nextInt();
if(firstTime && number==0){
System.out.println("error enter number first");
number = -1;
continue;
}
firstTime = false;
total=total+number;
counter=counter+1;
average=(total)/counter;
} while (number!=0);
System.out.println("The average of all numbers entered is: "+average);
}
}
Here is a simple program that extends on yours but uses nextDouble() instead of nextInt() so that you can enter numbers with decimal points as well. It also prompts the user if they have entered invalid input (something other than a number):
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Java_Paws's Average of Numbers Program");
System.out.println("======================================");
System.out.println("Usage: Please enter numbers one per line and enter a 0 to output the average of the numbers:");
double total = 0.0;
int count = 0;
while(scanner.hasNext()) {
if(scanner.hasNextDouble()) {
double inputNum = scanner.nextDouble();
if(inputNum == 0) {
if(count == 0) {
System.out.println("Error: Please enter some numbers first!");
} else {
System.out.println("\nThe average of the entered numbers is: " + (total / count));
break;
}
} else {
total += inputNum;
count++;
}
} else {
System.out.println("ERROR: Invalid Input");
System.out.print("Please enter a number: ");
scanner.next();
}
}
}
}
Try it here!

Can't figure why my program doesnt work

import java.util.Scanner;
public class pointSystem {
static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
int points;
int total = 0;
final int judges = 5;
System.out.println("Give points: ");
for(int i=0;i<judges;i++)
{
System.out.println("Give judge's "+ (i+1) + " points: ");
points = scanner.nextInt();
if(points<0 || points>20) {
System.out.println("You can only give points between 0-20");
System.out.println("Judge "+ (i+1) + " points: ");
points = scanner.nextInt();
}
total+=points;
}
System.out.println("Total points are "+total);
}
}
So it's totally a simple program where it asks the user to input points for 5 judges in total and then sums up the points at the end. But points can only be inserted between 0-20, if it goes outside of the range, it gives an error telling us to input again and continues to do so until we have give a valid input.
Now the program works pretty well except for a point that if I enter "22" for example, it asks again like intended but if I enter "22" once again, it lets it pass and skip to next judge.
How can I make it to keep asking until I have given a valid input before it moves to next judge? Please give a small explanation if you fix my code.
Also I'm supposed to make a small edit that when it sums up the points at the end, it minus the highest and lowest score away, summing up only the points between. So if the points are "3,5,8,9,20" it will take "3 and 20" away and only sums up "5,8 and 9" making it 22.
In your code, you have an if statement to check the input, but if your input doesn't pass your program will accept your next input without checking it.
To fix this, don't progress your program until your input is valid using a while loop, like this:
while(points<0 || points>20) {
System.out.println("You can only give points between 0-20");
System.out.println("Judge "+ (i+1) + " points: ");
points = scanner.nextInt();
}
total+=points;
}

java program that finds average with average method

I have a program that will average your numbers from the command line. Everything is in the main method.
1. The program should run allowing you to enter one number at a time and when you press enter it asks you for another number or offers the ability to press Q to get your average.
2. The program has a limit set to 20 numbers added. When you hit 21 the program notifies you that you added to many numbers and shuts down.
3. If you enter multiple numbers on the same line and press enter, for every number you enter it System.out.println a message once for every number instead of just once.
I would like to understand how to change the program to do these things.
How to get the System.out.println to only appear one time per entry.
How to get the program to output the average of 20 before it ends when someone enters 21
how do i change it to create a method for averaging outside of main then call on the averaging method inside the main.
import java.util.Scanner;
class programTwo {
public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
double sum = 0;
int count = 0;
System.out.println ("Enter your numbers to be averaged:");
String inputs = scan.nextLine();
while (!inputs.contains("q")) {
Scanner scan2 = new Scanner(inputs); // create a new scanner out of our single line of input
while(scan2.hasNextDouble()) {
sum += scan2.nextDouble();
count += 1;
System.out.println("Please enter another number or press Q for your average");
}
if(count == 21)
{
System.out.println("You entered too many numbers! Fail.");
return;
}
inputs = scan.nextLine();
}
System.out.println("Your average is: " + (sum/count));
}
1.
scan2.hasNextDouble()
is parsing the line which contains multiple entries so it must be removed in the while loop. You can parse yourself using string tokenize and print the message only once.
2 . Simply add this line:
System.out.println("Your average is: " + (sum/count));
before returning in if condition to print the average before quitting.
3 . that really depends on what kind of function would you like. May be you can create a function that takes an array of numbers and prints out their average or maybe you want something else.
one possible function:
public double findAverage(ArrayList<Integer> numbers){
int sum=0;
for (Integer i: numbers){
sum+=i;
}
return sum/(double)numbers.size();
}
You can try with the following:
public static void main(String[] args){
if(args.length==20)
{
int sum=0;
sum += Integer.parseInt(args[0]); //do this for 20 array elements using loop
// do required calculation
}
else //print error message
}

I need of assistance with array assigning user inputs to an array, and do-while loop repeat

I'm having a few problems with my code, this is the over all goal of the program.
One of your professors hears of your emerging programming expertise and asks you to write a SINGLE program that can be used to help them with their grading. The professor gives three 50-point exams and a single 100-point final exam. Your program will prompt the user for the student’s name, entered as Firstname Lastname (i.e. Bob Smith), the student’s 3-exam scores and 1-final exam score (all whole numbers). Class size varies from semester to semester, but 100 is the limit (declare as a constant).
Read in information for ALL students before doing any calculations or displaying any output. Verify that the 3 exam scores are between 0-50 points and that the final is between 0-100 as they are entered. Declared minimums and maximums as constant so that they can easily be updated, as needed. If invalid, display an error message and allow the user to re-enter that invalid score. Once all student info is read in, display each student’s name in the format LASTNAME, FIRSTNAME (all uppercase), the student’s exam percentage (total of all exams plus final / total possible) to 1 decimal and the student’s final grade.
This is what I have:
import java.util.*;
import java.text.*;
public class Proj4 {
public static void main(String[] args){
Scanner s= new Scanner(System.in);
String input;
String again = "y";
final int MAX_STUDENTS = 100;
final int MIN_EXAM = 0;
final int MAX_EXAM = 50;
final int MIN_FINAL = 0;
final int MAX_FINAL = 100;
String[] names = new String[MAX_STUDENTS];
int [] exams = new int[MAX_STUDENTS * 4];
int student = 1;
do
{
System.out.print("PLease enter the name of student " + student + ": " );
for (int k = 0; k < 1; k++) {
names[k] = s.nextLine().toUpperCase();
}
for ( int i = 0; i < 4; i++){
if(i==3){
System.out.print("Please enter score for Final Exam: ");
exams[i] = s.nextInt();
}
else{
System.out.print("Please enter score for Exam " + (i+1) + ": ");
exams[i] = s.nextInt();
if((exams[0]<MIN_EXAM||exams[0]>MAX_EXAM)||(exams[1]<MIN_EXAM||exams[1]>MAX_EXAM)||(exams[2]<MIN_EXAM||exams[2]>MAX_EXAM)){
System.out.println("Invalid enter 0-50 only...");
System.out.print("Please re-enter score: ");
exams[i] = s.nextInt();
}
else if(exams[3]<MIN_FINAL||exams[3]>MAX_FINAL){
System.out.println("Invalid enter 0-100 only...");
System.out.print("Please re-enter score: ");
exams[i] = s.nextInt();
}
}
}
System.out.print("do you wish to enter another? (y or n) ");
again = s.next();
if(again!="y")
student++;
}while (again.equalsIgnoreCase ("y"));
System.out.println("***Class Results***");
System.out.println(names[1] + "," + names[0] + " " + "Exam Percentage: "+ ((exams[0]+exams[1]+exams[2]+exams[3])/(MAX_EXAM*3+MAX_FINAL)));
}
}
The problems i have have are:
figuring out how to assign the user entered test scores beyond just the first student, i believe i have it set up correct for just one, but it runs into a problem when i would move on to the second student.
For some reason that I cannot figure out the line
System.out.print("do you wish to enter another? (y or n) ");
again = s.next();
doesn't allow me to enter anything, not y not n not anything, so my program effectively ends there, it doesn't make sense to me because I've done it exactly like that before and it has worked.
other than that, if there are any other problems that you can see with my code pointing them out would be extremely helpful.
Thank you
EDIT-
new problem i am having, after changing to
if(!again.equalsIgnoreCase("y"))
student++;
}while (again.equalsIgnoreCase ("y"));
it lets me type things in now, but after i type in y it prints the next line as
Please enter the name of student 1: Please enter score for Exam 1:
I don't know why or what i need to change to fix it, any suggestions?
`if(again!="y")` is the culprit here
You should use equals() method to check string equality.
if(!again.equals("y"))
If you compare Strings in Java using the == or != operators then you are not actually comparing the values. Instead you are testing if the two Strings are the same Object.
This post explains String comparison well.
To do what you want, change if (again != "y") to if(! (again.equalsIgnoreCase("y")) )
EDIT
I believe your new problem stems from the first for loop you do inside your do loop. Each time you type "y" at the end of your do/while you are going to execute the entire
for (int k = 0; k < 1; k++) {
loop again. This is why after you type "y" you are seeing Please enter the name of student 1: Please enter score for Exam 1:
A "solution" to your new issue would be to make it so the outer for enclosed the inner one, looping through 4 exams for each student usually referred to as a "double for" or "nested for loop".
That said you would then be presented with the issue of having all the exams for ALL students in a single array.
I think now is the time to sit down and put some serious thought into the design of your program. It would be much easier for you if you used a Student object to represent a student and hold their exam scores, IMO. Then you could create an array of Students as opposed to two different arrays you have now.
Here are some "starter" steps (Not necessarily a complete list):
Make a Student class that has variables for the student's first & last name, as well as an array to hold that Students exam scores
In your main class create an ArrayList to hold all of the new Student objects you will be creating.
Do your do/while loop. At the beginning of the loop create a new Student object. Then ask for the Students name and exam scores (note that if you KNOW there will only be the 4 exam scores you don't have to do any extra logic there. You can simply ask for the 4 exam scores using a for loop, or if you want all at one time. if there are a variable number of scores you will have to do some sort of check)
Add the new Student you have created to the ArrayList of Students.
Once the person selects "n", loop through the ArrayList and print the information for each Student!
Your for (int k = 0; k < 1; k++) loop will execute only once (for one student) because you have it set up to execute only while k < 1, which will happen only once. As soon, as you increase k to 1, the loop will stop. I would change it to for (int k = 0; k < MAX_STUDENTS; k++) to make sure it will loop through until you reach the max number of students allowed.

In Java, is it possible to use some sort of while loop (or anything) to determine the amount of prompts for input?

public static void main (String [] args)
{
// declare variables, capture input
String input, name = JOptionPane.showInputDialog("Please " +
"enter your first and last name.");
double testScore1, testScore2, testScore3, average;
// capture input, cast, and validate input
input = JOptionPane.showInputDialog("What is the score " +
"of your first test?");
testScore1 = Double.parseDouble(input);
while (testScore1 < 1 || testScore1 > 100)
{
input = JOptionPane.showInputDialog("This test score is not " +
"between 1 and 100. \nPlease enter a test score in " +
"this range:");
testScore1 = Double.parseDouble(input);
}
input = JOptionPane.showInputDialog("What is the score " +
"of your second test?");
testScore2 = Double.parseDouble(input);
while (testScore2 < 1 || testScore2 > 100)
{
input = JOptionPane.showInputDialog("This test score is not " +
"between 1 and 100. \nPlease enter a test score in " +
"this range:");
testScore2 = Double.parseDouble(input);
}
input = JOptionPane.showInputDialog("What is the score " +
"of your third test?");
testScore3 = Double.parseDouble(input);
while (testScore3 < 1 || testScore3 > 100)
{
input = JOptionPane.showInputDialog("This test score is not " +
"between 1 and 100. \nPlease enter a test score in " +
"this range:");
testScore3 = Double.parseDouble(input);
}
// calculate average and display output
average = (testScore1 + testScore2 + testScore3)/3;
JOptionPane.showMessageDialog(null, name + ", your average score is: " + average);
}
First off, I'm a beginner programmer. My terminology and jargon are quite lacking, so bear with me.
I'm writing a program to capture 3 test scores then validate them using a while loop (must be within the 1-100 range). The test scores are then averaged and the output displays the average. Pretty simple stuff.
I'm wanting to find a way, if possible, to capture the number of test scores, then from there, capture each actual score. For example, the program asks "How many tests are being computed for average?", then take that number and have it be the same amount of times the program prompts, "Please enter test score (1):" or something along those lines. So for further clarity, if the user typed 4 for number of tests, then the prompt for inputting the score would show up 4 times.
I feel the above code is redundant by using a while loop for each score and at that, limited because the program is only meant for 3 scores. Any help is much appreciated and feel free to critique anything else in the code.
Yes you can.
What you need is a nested loop. In pseudo code:
while(condition)
{
int numberOfInput = getInput() ; //get the input from the user
for(int i =0 ; i < numberOfInput; i++) //iterate for the amount of prompts required
prompt() ; //get input
}
function prompt
while (testScore1 < 1 || testScore1 > 100)
{
input = JOptionPane.showInputDialog("This test score is not " +
"between 1 and 100. \nPlease enter a test score in " +
"this range:");
testScore1 = Double.parseDouble(input);
}
Short answer:Yes, it is possible.
Option 1: Initially ask the user how many scores they are planning on entering, and store that in an int variable.
For example:
Ask user how many scores to enter.
Check the response, and store it in an int variable.
Create a double variable to add the scores (initialize it to 0.0)
Use a for loop, asking for the score;
Evaluate the score to ensure it's a valid number
If it's not a valid number, prompt the user again (this is still within
the same iteration, not a different iteration)
If it's a valid number, add it to the total scores variable
Once loop is exhausted, just divide the two variables (since the total
scores is a double, your answer will automatically be a double)
Display the answer.
Option 2: Use a sentinel-loop (the user has to enter a letter -usually 'Q' or 'N'- or something to exit the loop)
Create an int variable to store total loops (initialize to 0).
Create a double variable to add the scores (initialize it to 0.0)
Use a for loop, asking for the score;
Check if the value is the quit character
If it is not
Evaluate the score to ensure it's a valid number
If it's not a valid number, prompt the user again (this is still within
the same iteration, not a different iteration)
If it's a valid number, add it to the total scores variable and increment
the total loops variable by 1.
If it is
just divide the two variables (since the total
scores is a double, your answer will automatically be a double)
Display the answer.
Hope it helps.
In http://korada-sanath.blogspot.in/p/discussion-on-tech-topics.html, there is a pseudo code which illustrates similar problem with basic Java programming skills. In that in looping section you can simply add a check whether user entered score is in range 1-100 or not. If not, you can decrease loop variable by '1' so that user can enter his score one more time...
For further illustration please add below code in looping section of code present in above mentioned link.
instead of directly assigning user entered value to your testScores array, you can use one temp var and then can assign if user entered score in range.
Double temp = Double.parseDouble(br.readLine());
if(temp > 1 && temp < 100) {
testScores[loopVar] = temp;
} else {
loopVar--;
}

Categories