I'm trying to create this rather simple program for my java class. Everything is working, except for when I tried to have an input loop. I've never done that before, and it's ignoring every other input. Here is the problem prompt:
B. Ch. 4 – Average - Write a program that will read an unspecified number of integer grades and find the summary total and average. Print grades, total and average. The last record will be the trailer record of -1. Also output the final letter grade per syllabus grading scale.
And here is the code:
import java.util.Scanner;
public class Average
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
float counter = 0;
float accum = 0;
float addAccum = 0;
float tempLoop = 0;
System.out.println("Please Enter Grade, Enter -1 to Finish: ");
while (tempLoop != -1)
{
addAccum = in.nextFloat();
counter++;
accum = addAccum + accum;
tempLoop = in.nextFloat();
}
float avgGrade = accum / counter;
if(avgGrade >= 90)
{
System.out.println("\nYour Grade is: " + "A");
}else if(avgGrade >=80)
{
System.out.println("\nYour Grade is: " + "B");
}else if(avgGrade >=70)
{
System.out.println("\nYour Grade is: " + "C");
}else if(avgGrade >=60)
{
System.out.println("\nYour Grade is: " + "D");
}else
{
System.out.println("\nYour Grade is: " + "F");
}
System.out.println("\nGrade Total: " + accum);
System.out.println("\nCounter Num :" + counter); // for testing only
System.out.println("\nAverage Grade: " + avgGrade);
}
}
This is the console input/output:
Please Enter Grade, Enter -1 to Finish:
100
100
100
100
100
100
-1
-1
Your Grade is: C
Grade Total: 299.0
Counter Num :4.0
Average Grade: 74.75
You have in.nextFloat() twice in your while loop.
Change your logic to look for -1 first and then process the input.
Something like :
tempLoop = in.nextFloat();
while(tempLoop != -1){
sum += tempLoop;
tempLoop = in.nextFloat();
}
Hope this helps.
What you're doing is reading twice;
while (tempLoop != -1)
{
addAccum = in.nextFloat(); // Once Here
counter++;
accum = addAccum + accum;
tempLoop = in.nextFloat(); // Again Here
}
Thus only half of the data is being processed;
You'll need to read the first value before entering the loop, and then only read once at the end before checking that the new value is not -1
To avoid reading twice and reading inside the loop, or add ugly break statements, i would do it like this:
while ((addAccum = in.nextFloat()) != -1) {
counter++;
accum = addAccum + accum;
}
Related
My issue comes up when I enter an number where i have the illegal score prompt, it still adds a number to my counter and the number to the total so the average gets thrown off. Ive been wracking my brain and tried almost everything to figure it out. The code is a little sloppy because I haven't cleaned it up yet, I'm just trying to get the moving parts sorted out first.
public class StudentSentinel {
public static void main(String[] args) {
double score;
double total = 0.0;
double average;
int scoreCount = 0;
// create the Scanner object. Name it stdin
Scanner stdin = new Scanner(System.in);
// title at the top of the output
System.out.println(" student score report");;
// read the first score
System.out.printf("Enter a score (1-100, -1 to quit)" +
": ", scoreCount);
score = stdin.nextDouble();
scoreCount++;
while (score != -1.0) {
total += score;
System.out.printf("Enter a score (1-100, -1 to quit)" +
": ", scoreCount);
scoreCount++;
score = stdin.nextDouble();
if (score < -1)
System.out.println("Illegal score. Try again");
else if (score > 100) {
System.out.println("Illegal score. Try again");
}
// increment the loop counter
}
// end of for loop
average = total / scoreCount;
System.out.printf("\nThe average score for %d students is %8.2f\n",
scoreCount, average);
} // end of main
} // end of class definition
First check that the score is legal, then increment the counter and add it to your total. You can also assign score and check that isn't -1 with a single operation. And always use braces (even if they're optional). Like,
// read the first score
System.out.printf("Enter a score (1-100, -1 to quit)" + ": ", scoreCount);
while ((score = stdin.nextDouble()) != -1.0) {
if (score < -1 || score > 100) {
System.out.println("Illegal score. Try again");
} else {
scoreCount++;
total += score;
}
System.out.printf("Enter a score (1-100, -1 to quit)" + ": ", scoreCount);
}
Try this code out. It works for me:
public class StudentSentinel {
public static void main(String[] args) {
double score;
double total = 0.0;
double average;
int scoreCount = 0;
// create the Scanner object. Name it stdin
Scanner stdin = new Scanner(System.in);
// title at the top of the output
System.out.println(" student score report");;
// read the first score
System.out.printf("Enter a score (1-100, -1 to quit)" +
": ", scoreCount);
score = stdin.nextDouble();
scoreCount++;
total += score;
while (score != -1.0) {
System.out.printf("Enter a score (1-100, -1 to quit)" +
": ", scoreCount);
scoreCount++;
score = stdin.nextDouble();
if (score < -1) {
System.out.println("Illegal score. Try again");
continue;
}else if (score > 100) {
System.out.println("Illegal score. Try again");
continue;
}
total += score;
// increment the loop counter
}
// end of for loop
average = total / scoreCount;
System.out.printf("\nThe average score for %d students is %8.2f\n",
scoreCount, average);
} // end of main
}
This is the task:
Display the usage message "Please input test scores with values between 0-100.
Enter 999 to finish."
Accept test scores within the range 0-100. If the number is out of range, display the message "Invalid Test Score", disregard that input and continue collecting values
Stop collecting test scores when the user inputs the number 999
Once all values have been entered, display the number of scores entered, the lowest score, the highest score, and the average.
Sample output for input: 57 -2 98 13 85 77 999
And this is my solution:
import java.util.Scanner;
public class TestScoreStatistics {
public static void main(String[] args)
{
int max=0;
int min=999;
int avg=0;
int count=0;
int sum=0;
int num;
Scanner scan=new Scanner(System.in);
System.out.println("Please input test scores with values between 0-100.\nEnter 999 to finish.");
num=scan.nextInt();
int temp=num;
do
{
if(num==999)
System.exit(0);
if(num>=0 && num<=100)
{
count++;
sum+=num;
if(num>max )
max=num;
if(num<min)
min=num;
}
} while((num=scan.nextInt())!=999);
System.out.println("Test Statistics:");
System.out.println("Number of tests: "+count);
System.out.println("Lowest: "+min);
System.out.println("Highest: "+max);;
System.out.printf("Average: " + sum/count);
}
}
but when input is 999 the output should be
Test Statistics:
Number of Tests: 0
Lowest: 0
Highest: 0
Average: 0
how do I do that?
This is what i would do. If it is as assigment for your programming classes, I would suggest replacing the lines with collections etc. with some other code (you can find that on stackoverflow)
List<Integer> scores = new ArrayList<>();
Scanner scan = new Scanner(System.in);
System.out.println("Please input test scores with values between 0-100. Enter 999 to finish.");
int num = scan.nextInt();
do {
if (num == 999)
break;
if (num >= 0 && num <= 100) {
scores.add(num);
}
}
while ((num = scan.nextInt()) != 999);
if (scores.size() != 0) {
System.out.println("Test Statistics:");
System.out.println("Number of tests: " + scores.size());
System.out.println("Lowest: " + scores.indexOf(Collections.min(scores)));
System.out.println("Highest: " + scores.indexOf(Collections.max(scores)));
System.out.printf("Average: " + scores.stream().mapToInt(Integer::intValue).sum() / scores.size());
} else {
System.out.println("Test Statistics:");
System.out.println("Number of tests: 0");
System.out.println("Lowest: 0 *or write whatever you want here");
System.out.println("Highest: 0");
System.out.printf("Average: 0");
}
You might want to consider changing:
if(num==999)
System.exit(0);
to:
if(num==999)
break;
It will cause exiting do-while loop instead of finishing a program when your first input is "999". The problem you will need to solve then is dividing by 0 here:
System.out.printf("Average: " + sum/count);
You can change it to something like this:
if (count == 0) {
System.out.printf("Average: 0"); // Show average as 0 here, when count is equal to 0.
} else {
System.out.printf("Average: " + sum / count);
}
or something similar what you need to perform instead of dividing by 0 there.
I am trying to create a college gpa calculator. The program first asks for the number of classes, the amount of credits for each class, and then for the grade for each class. The program works when the each class has the same amount of credits but does not work when there are different amounts of credits for each class. I have tried debugging the program by including print statements that show the values as the program runs and I have determined that credits only records the last inputted value. Is this just how .nextDouble() works or am I making a mistake? How would I go about fixing this problem? I am also fairly new to Java so if I am making a simple mistake there's a reason why.... Thanks
import java.util.*;
public class Calculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("This program calculates your college GPA.");
System.out.println("Enter the number of classes you've taken this quarter/semester:");
int classes;
classes = input.nextInt();
double gradePoint = 0;
double credits = 0;
double totalCredits = 0;
String grades;
double gpa = 0;
double total = 0;
// for loop record number of credits per class
for (int i = 0; i < classes; i++) {
Scanner input2 = new Scanner(System.in);
if (i > 0) {
// user will be asked this second
System.out.println("Enter next amount of credit hours:");
}
else {
// user will be asked this first
System.out.println("Enter the number of credits for each class one by one:");
}
credits = input2.nextDouble();
System.out.println("credits:" + credits);
totalCredits += credits;
System.out.println("totalcredits:" + totalCredits);
}
System.out.println("credits:" + credits);
// for loop to record grades input and calculate gpa
for (int b = 0; b < classes; b++) {
System.out.println("credits:" + credits);
Scanner input3 = new Scanner(System.in);
if (b > 0) {
System.out.println("Enter your next grade:");
}
else {
System.out.println("To receive your GPA, enter your grades one by one:");
}
grades = input3.nextLine();
// if statements will convert letter grades to grade points
// grade points will then be multiplied by their respective amount of credits
if (grades.equals("A+")) {
gradePoint=4.0;
total += (gradePoint*credits);
}
else if (grades.equals("A")) {
gradePoint=4.0;
total += (gradePoint*credits);
}
else if (grades.equals("A-")) {
System.out.println("credits:" + credits);
gradePoint=3.7;
System.out.println("gradePoint:" + gradePoint);
total += (gradePoint*credits);
System.out.println("total:" + total);
}
else if (grades.equals("B+")) {
System.out.println("credits:" + credits);
gradePoint=3.3;
System.out.println("gradePoint:" + gradePoint);
total += (gradePoint*credits);
System.out.println("total:" + total);
}
else if (grades.equals("B")) {
System.out.println("credits:" + credits);
gradePoint=3.0;
System.out.println("gradePoint:" + gradePoint);
total += (gradePoint*credits);
System.out.println("total:" + total);
}
else if (grades.equals("B-")) {
System.out.println("credits:" + credits);
gradePoint=2.7;
System.out.println("gradePoint:" + gradePoint);
total += (gradePoint*credits);
System.out.println("total:" + total);
}
else if (grades.equals("C+")) {
gradePoint=2.3;
total += (gradePoint*credits);
}
else if (grades.equals("C")) {
gradePoint=2.0;
total += (gradePoint*credits);
}
else if (grades.equals("C-")) {
gradePoint=1.7;
total += (gradePoint*credits);
}
else if (grades.equals("D+")) {
gradePoint=1.3;
total += (gradePoint*credits);
}
else if (grades.equals("D")) {
gradePoint=1.0;
total += (gradePoint*credits);
}
else if (grades.equals("D-")) {
gradePoint=0.7;
total += (gradePoint*credits);
}
else if (grades.equals("F")) {
gradePoint=0;
total += (gradePoint*credits);
}
else {
System.out.println("Invalid input.");
}
// gpa algorithm
gpa = total/totalCredits;
System.out.println("totalCredits" + totalCredits);
System.out.println("gpa:" + gpa);
}
System.out.println("GPA: " + gpa);
}
}
Also, when inputted:
3
5
5
3
A+
B+
C-
The program outputs the following:
This program calculates your college GPA.
Enter the number of classes you've taken this quarter/semester:
3
Enter the number of credits for each class one by one:
5
credits:5.0
totalcredits:5.0
Enter next amount of credit hours:
5
credits:5.0
totalcredits:10.0
Enter next amount of credit hours:
3
credits:3.0
totalcredits:13.0
credits:3.0
credits:3.0
To receive your GPA, enter your grades one by one:
A+
totalCredits13.0
gpa:0.9230769230769231
credits:3.0
Enter your next grade:
B+
credits:3.0
gradePoint:3.3
total:21.9
totalCredits13.0
gpa:1.6846153846153844
credits:3.0
Enter your next grade:
C-
totalCredits13.0
gpa:2.076923076923077
GPA: 2.076923076923077
(the correct gpa should be 3.2)
The problem in your credits variable, when you input
5
5
3
the last input which is 3 is stored into your credits variable and the same value is going through your 2nd loop which you're using for grades.
Solution 1:
Use array credits array and input your all classes credits into this array so that you can access different credits into your grades inputs.
Solution 2:
Use only one loop for credits and grades and input one by one I make some code for you.
here is the code.
for (int b = 0; b < classes; b++) {
Scanner input3 = new Scanner(System.in);
System.out.println("Enter credit hours for class :"+(b + 1));
credits = input2.nextDouble();
System.out.println("credits:" + credits);
totalCredits += credits;
System.out.println(" ");
System.out.println("Enter grade for class : "+(b + 1));
grades = input3.nextLine();
}
Inputs:
3 //number of classes
5 //first class credits
A+ //first class grade
5 .
B+ .
3 .
c- ..........
Output:
gpa:3.2
GPA: 3.2
this one just is hurting my brain. http://programmingbydoing.com/a/adding-values-in-a-loop.html
Write a program that gets several integers from the user. Sum up all the integers they give you. Stop looping when they enter a 0. Display the total at the end.
what ive got so far:
Scanner keyboard = new Scanner(System.in);
System.out.println("i will add");
System.out.print("number: ");
int guess = keyboard.nextInt();
System.out.print("number: ");
int guess2 = keyboard.nextInt();
while(guess != 0 && guess2 != 0)
{
int sum = guess + guess2;
System.out.println("the total so far is " + sum);
System.out.print("number: ");
guess = keyboard.nextInt();
System.out.print("number: ");
guess2 = keyboard.nextInt();
System.out.println("the total so far is " + sum);
}
//System.out.println("the total so far is " + (guess + guess2));
}
Declare the int sum variable outside of the while loop and only have one guess = keyboard.nextInt() inside the loop. Add the user's guess to the sum in the loop as well.
Then after the loop output the user's sum.
I.e.:
int sum;
while(guess != 0)
{
guess = keyboard.nextInt();
sum += guess;
}
System.out.println("Total: " + sum");
Edit: also remove the guess2 variable, as you will no longer need it.
The code will be as below :
public static void main(String[] args) throws Exception {
Scanner keyboard = new Scanner(System.in);
int input = 0;
int total = 0;
System.out.println("Start entering the number");
while((input=keyboard.nextInt()) != 0)
{
total = input + total;
}
System.out.println("The program exist because 0 is entered and sum is "+total);
}
Programming by Doing :)
int x = 0;
int sum = 0;
System.out.println("I will add up the numbers you give me.");
System.out.print("Number: ");
x = keyboard.nextInt();
while (x != 0) {
sum = x + sum;
System.out.println("The total so far is " + sum + ".");
System.out.print("Number: ");
x = keyboard.nextInt();
}
System.out.println("\nThe total is " + sum + ".");
import java.util.Scanner;
public class AddingInLoop {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int number, total = 0;
System.out.print("Enter a number\n> ");
number = keyboard.nextInt();
total += number;
while (number != 0) {
System.out.print("Enter another number\n> ");
number = keyboard.nextInt();
total += number;
}
System.out.println("The total is " + total + ".");
}
}
You first prompt the user to enter a number. Then you store that number into total (total += number OR total = total + number). Then, if the number entered wasn't 0, the while loop executes. Every time the user enters a nonzero number, that number is stored in total ( the value in total is getting bigger) and the while loops asks for another number. If and when a user enters 0, the while loop breaks and the program displays the value inside total. :D I myself am a beginner and had a bit of an issue with the logic before figuring it out. Happy coding!
When i run this, the reader only reads and displays every other line. What am i doing wrong?
while (imputFile.hasNext()) {
grade = imputFile.nextDouble();
System.out.println(grade);
if (grade < 0 || grade > 100)
System.out.print("Grade " + grade + " was invalid and ignored");
else {
numberOfGrades++;
sum += imputFile.nextDouble();
}
}
averageGrade = sum/numberOfGrades;
System.out.println("There were "+ numberOfGrades + " valid grades.");
System.out.printf("%3.2f",averageGrade);
You are using imputFile.nextDouble() in your loop twice:
grade = imputFile.nextDouble();
//....
sum += imputFile.nextDouble();
Try changing last line to
sum += grade;
to use already read value, not to read next one.