I've seen several average calculators but none with this specific function.
Basically, I want it to ask "How many numbers would you like to average?" then "Enter your number" and continue to prompt "Enter your number" after each entry until the "How many numbers..." quantity is fulfilled. I know it's a count-loop (sorry if my jargon is off...I'm only in my second semester of computer programming) but I don't know how to set it up. Thanks in advance for your answers. Here's what I have so far:
import java.util.Scanner;
public class TestScoreApp
{
public static void main(String[] args)
{
// welcome the user to the program
System.out.println("Welcome to the Test Average Calculator!");
System.out.println(); // print a blank line
// display operational messages
System.out.println("Please enter test scores that range from 0 to 100.");
System.out.println(); // print a blank line
// initialize variables and create a Scanner object
int scoreTotal;
int scoreCount;
int testScore;
Scanner sc = new Scanner(System.in);
// perform calculations until choice isn't equal to "y" or "Y"
String choice = "y";
while (!choice.equalsIgnoreCase("n"))
{
// get the number of grades to be averaged from the user
System.out.print("How many scores would you like to average? ");
scoreCount = sc.nextInt();
// get the input from the user
System.out.print("Enter score: ");
testScore = sc.nextInt();
// accumulate score count and score total
if (testScore <= 100)
{
scoreTotal = scoreTotal + testScore;
}
else if (testScore >= 100)
System.out.println("Invalid entry, not counted");
// display the score count, score total, and average score
double averageScore = scoreTotal / scoreCount;
String message = "\n" +
"Score count: " + scoreCount + "\n"
+ "Score total: " + scoreTotal + "\n"
+ "Average score: " + averageScore + "\n";
System.out.println(message);
System.out.print("Would you like to average more grades? (y/n): ");
choice = sc.next();
System.out.println();
}
}
}
Your approach is near about right except some mistakes. You want to take input until 'n' is pressed and then the average would be shown. That means the average calculation must be done outside the loop, when taking input ends.
If you want to take input with a predefined number from input instead of 'y'/'n' approach, you can reuse your while loop:
int numOfInput = sc.nextInt(); // how many number will be entered
while(numOfInput > 0) {
// take every input and add to total
--numOfInput;
}
// average calculation
Also, a little logical mistake in input validation check.
if (testScore <= 100) // for less or equal 100
{
scoreTotal = scoreTotal + testScore;
}
else if (testScore >= 100) // for greater or equal 100
System.out.println("Invalid entry, not counted");
Both condition checks whether the number is equal to 100, which is not expected. If you allow only number less than 100, then you could write:
if (testScore < 100) {
scoreTotal += testScore;
}
else {
System.out.println("Invalid entry, not counted");
}
So you want to average scoreCount items, or keep averaging until the user has input "n" ?
If it's the first case (As you've described in your question) and you want to average for scoreCount times, you need to change the condition on your while loop.
System.out.print("How many scores would you like to average? ");
scoreCount = sc.nextInt();
scoreTotal = 0;
for(int i=0; i<scoreCount; i++){
scoreTotal += sc.nextInt();
System.out.print("Okay please enter next...");
}
System.out.print("Average is " + scoreTotal/scoreCount);
If you want to do it with a while, just keep an index, int index=0;, increment the index on each iteration and check if you've exceeded the index.
while (index < scoreCount)
scoreTotal += sc.nextInt();
index++;
System.out.print("Average is " + scoreTotal/scoreCount);
That is what you need:
for( int i = 0; i < scoreCount; i++){
System.out.print("Enter score: ");
testScore = sc.nextInt();
}
The for loop creates integer i to hold its looping index
int i;
And each loop asks is i bigger than scoreCount and if not loop again.
i < scoreCount;
And after each loop it adds one to i.
i++
Related
I need to write a program that allows a student to enter up to 10 quiz scores, computes the average score, and then displays the letter grade based on the average. However, if the user enters 999 during the input of quiz scores, the program will terminate. This is the code block I wanted to insert a break statement into but I'm struggling to correctly incorporate grade[i] = 999 into my code without getting an error message. I think the issue may be that the 999 is an integer array value and is unrelated to the int i counter in the for loop.
for (i = 0; i < 10; i++) {
//prompts user to enter grade + displays counter value
System.out.print("Enter grade " + (i + 1) + " or enter 999 to quit: ");
//allows user input to be stored in variable grade
grade[i] = scanner.nextInt();
//adds new grade input to total grade to update variable gradeTotal
gradeTotal = gradeTotal + grade[i];
Assign the inputted value to a temporary variable, and then if it is 999 break the loop, else assign it the the array.
for (i = 0; i < 10; i++) {
System.out.print("Enter grade " + (i + 1) + " or enter 999 to quit: ");
int temp = scanner.nextInt();
if (temp == 999) {
break;
}
grade[i] = temp;
...
I'm creating a guessing game in Java using NetBeans. The guessing game allows the user to guess a number between 1 and 10. Each round they have 5 chances to guess the number. There are three rounds in the game. After the user finishes the game, stats are outputted with the minimum # of guess and maximum # of guesses.
The minimum guesses isn't working and it always outputs 1. Right now, I have the program set up so that it keeps track of how many times the user guesses per round. After each round, it compares this value to the min value and max value. The minGuess is set as 5 since it isn't possible to guess more than 5 times. The maxGuess is set as 1 since they will always guess one time or more than one time.
static void numberGuess(int guess, int randNum) { //creating a method to check if the user has guessed the correct number or if the guess should be higher or lower
if (guess < 0 | guess > 10) {
System.out.println("Please enter a valid number between 1 and 10.");
}
else if (guess == randNum) {
System.out.println("You guessed the number correctly");
}
else if (guess < randNum) {
System.out.println("Guess is too low");
}
else if (guess > randNum) {
System.out.println("Guess is too high");
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
/*Rational: This program allows a user to guess a number between 1 and 10 five times per round. There are three rounds in one game.
The program then outputs the stats for the game.
*/
//declaration
int userGuess; //creates a spot in memory for these variables
int numOfGuess = 0;
int invalidGuess = 0;
int minGuess = 5;
int maxGuess = 1;
int average;
Scanner Input = new Scanner (System.in); //creates an object in the scanner clas
//execution
System.out.println("Welcome to Super Guessing Game! Guess a random number between 1 and 10. There are three rounds with one guess each.");
loopOne: //labels the loop as loopTwo
for (int x = 1; x <= 3; x= x + 1 ) { //runs the loop for three rounds
System.out.println(" ");
System.out.println("Round " + x);
System.out.println("To exit the game at any point, enter a negative 1");
System.out.println(" ");
int randNum;
randNum = 1 + (int)(Math.random() * ((10 - 1) + 1)); //generates the random number
loopTwo: //labels the loop as loopTwo
for (int y = 1; y <= 5; y= y + 1) { //runs the loop five times (five guesses per round)
numOfGuess = numOfGuess + 1; //counts number of guesses user has made
System.out.println("Guess " + y + " out of 5");
System.out.println("Please guess a number between 1 and 10: ");
userGuess = Input.nextInt();
if (userGuess == -1){ //sentinel to let the user quit at any time
System.out.println("Thank you for playing");
break loopOne; //breaks out of the loops if the user wants to stop playing
}
numberGuess(userGuess, randNum); //calls the numberGuess method
if (y < minGuess) //compares to see if the minimum number of guesses is less that the number of guesses the user has made this round
minGuess = y;
if (y > maxGuess) //compares to see if the maximum number of guesses is greater than the number of guesses that the user has made this round
maxGuess = y;
if (userGuess <1 | userGuess > 10) { //keeps track of invalid guesses
invalidGuess = invalidGuess + 1;
}
if (userGuess == randNum) { //exits the round if the user guesses correctly
break;
}
}
}
average = numOfGuess / 3; //calculates the average number of guesses
System.out.println("Thanks for playing!"); //outputs the following
System.out.println("");
System.out.println("Number of Guesses Made: " + numOfGuess);
System.out.println("Average Number of Guesses: " + average);
System.out.println("Number of Invalid Guesses: " + invalidGuess);
System.out.println("Minimum Guesses Used: " + minGuess);
System.out.println("Maximum Guesses Used: " + maxGuess);
}
}
y starts at one, and is never less than one, thus minGuess is always one.
for (int y = 1; y <= 5; y= y + 1) {
...
if (y < minGuess)
minGuess = y;
...
}
Consider only updating minGuess and maxGuess upon a successful guess.
Your if statement is at the wrong place.
Your asking every time. also if the user isnt guessing the right number.
so just put it in ur numberguess method:
else if (guess == randNum) {
System.out.println("You guessed the number correctly");
if (y < minGuess) //compares to see if the minimum number of guesses is less that the number of guesses the user has made this round
minGuess = y;
if (y > maxGuess) //compares to see if the maximum number of guesses is greater than the number of guesses that the user has made this round
maxGuess = y;
}
package gradeAvg;
import java.util.Scanner;
//Grade Average calculater
public class GradeAvg {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
System.out.print("Please Enter the first grade being added to the average:");
double average = input.nextInt();
System.out.print("The average is now: " + average + " Please enter the second grade being averaged:");
average += input.nextInt() ;
System.out.print("The average is now: " + average + " Please enter the third grade being averaged:");
average += input.nextInt() / 2;
System.out.print("The average is now: " + average + " Please enter the fourth grade being averaged:");
average += input.nextInt() / 2;
System.out.print("The average is now: " + average + " Please enter the fifth grade being averaged:");
average += input.nextInt() / 2;
input.close();
System.out.print(average);
}
}
Hey guys, I'm really new to java, and pretty terrible at math, I'm supposed to be making a program that allows the user to input a value, have it averaged out, print it out, and then allow the input of another value, have it averaged, and print, and continue. Am i going wrong when I divide by 2 at the end of each input or what?
Average is the sum of all the numbers divided by the number of numbers in the sum.
What you are doing here is not average. You are adding the half of every new number to the total sum. I don't what you are doing here.
Just to make things more understandable, let's make a sum and a counter:
public class GradeAvg {
public static void main(String[] args) {
int sum;
int counter;
// ...
}
}
Each time you ask for a number, you increment the counter and add the new number to sum:
int newNumber;
// ask for input
newNumber = input.nextInt()
sum += newNumber;
counter++;
You can then output the average like this:
System.out.println("The average is: " + (double)sum / counter);
That's wrong. each number you add weight 50% against the other numbers.
you need to keep track of the count (number of elements) and the sum and each time divide the sum by the number of elements.
so each time you add a number the function should be:
(OLD_AVERAGE*OLD_COUNT+NEW_NUMBER)/(OLD_COUNT+1)
or just use SUM and COUNT and each time AVERAGE=SUM/COUNT.
inc. count by 1 every new number.
inc sum by the number entered.
complete working solution... hope it helps...
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double sum = 0;
int count = 1;
double average = 0;
System.out.print("Please Enter the " + count + " grade being added to the average:");
for (; count <= 5;) {
sum = sum + input.nextInt();
average = sum / count;
System.out.println("The average is now: " + average);
count++;
if (count <= 5)
System.out.println("Please enter the " + count + " grade being averaged:");
}
input.close();
}
This is a program to calculate average grades and I cant figure out whats wrong with my code. It is returning the wrong answer.
Editing post to remove personal information.
:
/**
* This program will calculate grade average of user input
* Date: 10/2/2015
*/
import java.util.Scanner;
public class GradeAVG {
public static void main(String[] args) {
avgGrade();
}
public static void avgGrade() {
Scanner keyboard = new Scanner (System.in);
double count = 0;
double avgGrade = 0 ;
double grade;
double total = 0;
System.out.println("Please input the grade");
grade = keyboard.nextDouble();
while(true){
System.out.println("Please input the grade");
grade= keyboard.nextDouble();
count = count + 1;
if (grade < 0) break;
total += grade;
avgGrade = total/count;
}
System.out.println ("Sum is " +total);
System.out.printf("The average of the %.0f grades are %.2f " ,count ,avgGrade);
}
}
Output:
Please input the grade
100
Please input the grade
50
Please input the grade
-9
Sum is 50.0
The average of the 2 grades are 50.00
Sum should have been 150 and average 75.
The problem is that you are reading a grade from the user before the while loop begins and you are ignoring this value afterwards.
You should remove those 2 lines and things will work as expected. I commented those lines in the snippet below to explicitely show you the problem.
public static void avgGrade() {
Scanner keyboard = new Scanner(System.in);
double count = 0;
double avgGrade = 0;
double grade;
double total = 0;
// System.out.println("Please input the grade");
// grade = keyboard.nextDouble();
while(true){
System.out.println("Please input the grade");
grade = keyboard.nextDouble();
count = count + 1;
if (grade < 0) break;
total += grade;
avgGrade = total/count;
}
System.out.println ("Sum is " +total);
System.out.printf("The average of the %.0f grades are %.2f " ,count ,avgGrade);
}
As a side note, you should always try to minimize the scope of each of your variable. Here, the grade variable is only use inside the while loop so you can directly write double grade = keyboard.nextDouble(); and remove the declaration in the beginning of the method.
You are not adding the first grade which you are accepting outside of the while loop to the total.
Also there is no point in incrementing the count, if the grade is not acceptable, so increment your count only after the grade check.
You can rewrite your while block something like
while (true) {
System.out.println("Please input the grade");
grade = keyboard.nextDouble();
if (grade < 0)
break;
count = count + 1;
total += grade;
}
avgGrade = total / count;
System.out.println("Sum is " + total);
System.out.printf("The average of the %.0f grades are %.2f ", count,
avgGrade);
}
Thanks guys. Here is the final code
/**
* This program will calculate grade average of user input
*
* Date: 10/2/2015
*/
import java.util.Scanner;
public class GradeAVG {
public static void main(String[] args) {
avgGrade()
}
public static void avgGrade()
{
Scanner keyboard = new Scanner (System.in);
double count = 0;
double avgGrade = 0 ;
double total = 0;
while(true){
System.out.println("Please input the grade");
double grade= keyboard.nextDouble();
if (grade < 0) break;
count = count + 1;
total += grade;
avgGrade = total/count;
}
System.out.println ("Sum is " +total);
System.out.printf("The average of the %.0f grades are %.2f " ,count ,avgGrade);
}
}
Several problems:
First, you do two assignments into grade before first reading from it (first one before the while loop and second inside the while loop), so the first input will be ignored entirely
Second, you increment the count variable before checking whether to break the while loop, so you end up with count higher by 1 than should be
Third, the average is computed inside the loop and will not be recalculated in the last (partial) iteration
The program will go like this:
input: 100, count: 0, total: 0, avg: 0
input was ignored
input: 50, count: 1, total: 50, avg: 50
input: -9, count: 2, total: 50, avg: 50
loop exit, but incremented count before; did not recalculate avg
This program will calculate the average grade for 4 exams using a for loop by prompting
the user for exam grades, one at a time, then calculate the average and display the result.
public class ExamsFor4 {
public static void main(String[] arguments) {
int inputNumber; // One of the exams input by the user.
int sum = 0; // The sum of the exams.
int i; // Number of exams.
Double Avg; // The average of the exams.
TextIO.put("Please enter the first exam: "); // get the first exam.
inputNumber = TextIO.getlnInt();
for ( i = 1; i <= 4; i++ ) {
sum += inputNumber; // Add inputNumber to running sum.
TextIO.put("Please enter the next exam: "); // get the next exam.
inputNumber = TextIO.getlnInt();
if (i == 4) {
Avg = ((double)sum) / i;
TextIO.putln();
TextIO.putln("The total sum for all " + i +" exams is " + sum);
TextIO.putf("The average for the exams entered is %1.2f.\n", Avg);
break;
}
}
} // end main ()
} // end class ExamsFor4
My result:
Please enter the first exam: 100
Please enter the next exam: 99
Please enter the next exam: 98
Please enter the next exam: 97
Please enter the next exam: 96
The total sum for all 4 exams is 394
The average for the exams entered is 98.50.
This would be correct except for the last print out of: 'Please enter the next exam: 96'
I tried putting the IF statement between the 'sum' line and the TextIO.put 'Enter next exam', but that isolates it.
Thanks, from a Network Dude trap in a Programmer's world.
You have what is called an off-by-one error, compounded by the fact that you're convoluting your loop logic unnecessarily.
With regards to the loop, I recommend two things:
Don't loop for (int i = 1; i <= N; i++); it's atypical
Do for (int i = 0; i < N; i++); it's more typical
Instead of checking for the last iteration to do something, refactor and take it outside of the loop
Related questions
What is exactly the off-by-one errors in the while loop?
See also
Wikipedia/Off-by-one error
On Double Avg
In Java, variable names start with lowercase. Moreover, Double is a reference type, the box for the primitive double. Whenever possible, you should prefer double to Double
See also
Java Language Guide/Autoboxing
JLS 5.1.7 Boxing Conversion and 5.1.8 Unboxing Conversion
Effective Java 2nd Edition, Item 49: Prefer primitives to boxed primitives
Related questions
What is the difference between an int and an Integer in Java/C#?
Java: What’s the difference between autoboxing and casting?
Why does int num = Integer.getInteger(“123”) throw NullPointerException?
Why does autoboxing in Java allow me to have 3 possible values for a boolean?
Is it guaranteed that new Integer(i) == i in Java? (YES!!!)
When comparing two Integers in Java does auto-unboxing occur? (NO!!!)
Java noob: generics over objects only? (yes, unfortunately)
Rewrite
Here's a way to rewrite the code that makes it more readable. I used java.util.Scanner since I don't think TextIO is standard, but the essence remains the same.
import java.util.*;
public class ExamsFor4 {
public static void main(String[] arguments) {
Scanner sc = new Scanner(System.in);
final int NUM_EXAMS = 4;
int sum = 0;
for (int i = 0; i < NUM_EXAMS; i++) {
System.out.printf("Please enter the %s exam: ",
(i == 0) ? "first" : "next"
);
sum += sc.nextInt();
}
System.out.printf("Total is %d%n", sum);
System.out.printf("Average is %1.2f%n", ((double) sum) / NUM_EXAMS);
}
}
An example session is as follows:
Please enter the first exam: 4
Please enter the next exam: 5
Please enter the next exam: 7
Please enter the next exam: 9
Total is 25
Average is 6.25
Note that:
Only necessary variables are declared
The loop index is local only to the loop
There are no cluttering comments
Instead, focus on writing clear, concise, readable code
If it makes sense to make something final, do so
Constants in Java is all uppercase
Related questions
Why does (360 / 24) / 60 = 0 in Java
Because it performs integer division. This is why the cast to (double) prior to the division in above code is necessary, so that it performs floating point division.
How does the ternary operator work?
This is the ?: operator in above code, also known as the conditional operator.
See also: JLS 15.25 Conditional Operator ?:
Change your end condition to be strictly less than 4 and put the code that prints out the total and average outside the loop.
You should probably put the if-statment outside the for-loop. That way you don't need the if-statement. Second the statement in the loop should be < 4 instead of <= 4.
public class ExamsFor4 {
public static void main(String[] arguments) {
int inputNumber; // One of the exams input by the user.
int sum = 0; // The sum of the exams.
int i; // Number of exams.
Double Avg; // The average of the exams.
TextIO.put("Please enter the first exam: "); // get the first exam.
inputNumber = TextIO.getlnInt();
for ( i = 1; i < 4; i++ ) {
sum += inputNumber; // Add inputNumber to running sum.
TextIO.put("Please enter the next exam: "); // get the next exam.
inputNumber = TextIO.getlnInt();
}
Avg = ((double)sum) / i;
TextIO.putln();
TextIO.putln("The total sum for all " + i +" exams is " + sum);
TextIO.putf("The average for the exams entered is %1.2f.\n", Avg);
break;
} // end main ()
}
Just making few changes in your code makes it work. But you should follow cleaner approach as proposed in some of answers.
public class ExamsFor4 {
public static void main(String[] arguments) {
int inputNumber; // One of the exams input by the user.
int sum = 0; // The sum of the exams.
int i; // Number of exams.
double Avg; // The average of the exams.
TextIO.put("Please enter the first exam: "); // get the first exam.
inputNumber = TextIO.getlnInt();
sum += inputNumber;
for ( i = 1; i < 4; i++ ) {
TextIO.put("Please enter the next exam: "); // get the next exam.
inputNumber = TextIO.getlnInt();
sum += inputNumber; // Add inputNumber to running sum.
}
Avg = ((double)sum) / i;
TextIO.putln();
TextIO.putln("The total sum for all " + i +" exams is " + sum);
TextIO.putf("The average for the exams entered is %1.2f.\n", Avg);
} // end main ()
} // end class ExamsFor4
import java.util.Scanner;
public class ExamsFor4 {
public static void main(String[] arguments) {
int sum = 0; // The sum of the exams.
int i = 1; // Number of exams.
double avg = 0; // The average of the exams.
Scanner in = new Scanner(System.in);
System.out.print("Please enter the first exam: ");
sum += in.nextInt();
i++;
while(i<=4){
System.out.print("Please enter the next exam: ");
sum += in.nextInt();
if(i==4)
break;// this line is so that it wont increment an extra time.
i++;
}
System.out.println("The total sum for all " + i +" exams is " + sum);
avg = ((double)sum/i);
System.out.println("The average for the exams entered is" + avg);
} // end main ()
} // end class ExamsFor4