The homework problem is to write a program that adds together all the scores from a class exam and find the average.
I have two questions. To find the average, you have to divide the total score by the number of test takers. I don't know how to record how many test takers there are.
Does the method for getting the average go in the while loop or outside the while loop?
import acm.program.*;
public class AvgScore extends ConsoleProgram {
public void run(){
println("This program averages the test scores of an exam until the SENTINEL is entered .");
int total = 0;
while(true) {
int score = readInt("enter the test score: ");
if (score == SENTINEL) break;
total += score;
}
println("the average for the class was");
}
private static final int SENTINEL = -1;
}
just add a count variable for every read
int count=0
while(true) {
int score = readInt("enter the test score: ");
if (score == SENTINEL) break;
total += score;
count++;
}
the calculate the average
double avg = (double)total/count;
Related
I need to write code that calculates the average of inputs (int) a user has entered. However, the problem is that I also have to allow the user to enter as many inputs as they want and stop when they enter a character(letter).
I can do this problem if there was a given limit I could use, but because the limit could be anything I am having trouble writing a formula that could calculate the average since the number of inputs could be different between any user.
import java.util.Scanner;
public class AvgGrades {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter as many student grades as you like. Enter a character to stop.");
float total=0, avg;
int grades = input.nextInt();
for (int i = 0; i < grades.length; i++) {
grades[i] = input.nextInt();
total = total + grades[i];
}
input.close();
avg = total/grades.length;
System.out.println("Average student grade is "+avg);
}
}
The inputs are:
30.0
45.6
23.8
78.75
90
92
67.5
10.65
88
c
The output should be:
Enter as many student grades as you like. Enter a character to stop.
Average student grade is: 58.477777777777774
My output is that the code just does not run.
Here's a sketch of the process. I'll leave for you the details of turning that into a complete program.
float total = 0;
int count = 0;
while (scanner.hasNextFloat()) {
float num = scanner.nextFloat();
total += num;
count++;
}
float average = total / count;
You don't need to store the individual numbers.
// Create a full program in eclipse that will ask the user how times would you like to loop for. It will ask in the for loop for a rate in double value and a time in integer value. It will calculate the distance for each of the times you enter in the rate and the time.//
my current output gives me the correct answer if i only want to put in once, as it only has to run the program once. Whenever i input more than 1, It starts acting weird and thats the best way i can explain it because i don't know whats wrong with it.
Here is one random output
How many times would you like to calculate the distance.
12
Enter rate
2
Enter time
13
The distance is 26.0
Enter rate
12
Enter time
12
The distance is 144.0
How many times would you like to calculate the distance.
1
Enter rate
12
Enter time
1
The distance is 12.0
// my actual code
import java.util.Scanner;
public class NTC {
public static void main(String[] args){
Scanner kb=new Scanner(System.in);
int loop = 10;
double rate=0;
int time=0;
int count;
double distance = rate*time;
for (count = 0; count <= loop; count++) {
System.out.println("How many times would you like to calculate the distance.");
loop = kb.nextInt();
for(rate=0; rate <loop;rate++)
{
System.out.println("Enter rate");
rate = kb.nextDouble();
for(time=0; time <loop;time++)
{
System.out.println("Enter time");
time = kb.nextInt();
System.out.println("The distance is "+rate*time);
}
You need to have only one for loop:
import java.util.Scanner;
public class NTC
{
public static void main(String[] args)
{
Scanner kb=new Scanner(System.in);
int loop = 10;
double rate=0;
int time=0;
int count;
double distance = rate*time;
System.out.println("How many times would you like to calculate the distance.");
loop = kb.nextInt();
for (count = 0; count < loop; count++)
{
System.out.println("Enter rate");
rate = kb.nextDouble();
System.out.println("Enter time");
time = kb.nextInt();
System.out.println("The distance is "+(rate*time));
}
}
}
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
I need to write a program in Java that can take the multiples of five up to a value given by the user, and then add all of the multiples together. I need to write it with a while loop.
Here's what I have so far:
import java.util.Scanner;
public class SummationOfFives {
public static void main(String[] args){
//variables
double limit;
int fives = 0;
//Scanner
System.out.println("Please input a positive integer as the end value: ");
#SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
limit = input.nextDouble();
//While Loop
while ((fives+5)<=limit)
{
fives = fives+5;
System.out.println("The summation is: "+fives);
}
}
}
When I run this program however, all it gives me is the multiples:
Please input a positive integer as the end value:
11
The summation is: 5
The summation is: 10
You're nearly there! Think about what your output is telling you. In your while loop, fives is the next multiple of 5 on each iteration. You're not adding it to a total variable anywhere.
So - define a total before the loop e.g.
int total = 0;
keep adding to it in the loop (where your System.out.println is now) e.g.
total = total + fives;
output the total after the loop e.g.
System.out.println(total);
I added a total variable into your loop that will accumulate the value of all of the summations.
int counter =1;
int total = 0;
//While Loop
while ((fives+5)<=limit)
{
total = counter*5;
counter++;
fives = fives+5;
System.out.println("The summation is: "+fives);
System.out.println("The total is: "+total);
}
The summation you do in fives is wrong. You need another variable multiple initialised to 0 that you will increment by 5 at each step of the loop. The stop condition in the while is (multiple < limit). Then fives are the sum of the multiples.
double limit;
int fives = 0;
int multiple = 0
//While Loop
while (multiple<=limit)
{
multiple += 5;
fives = fives + multiple;
System.out.println("So far, the summation is: "+fives);
}
So I'm trying to make a program where it averages out your golf scores. I edited a standard averaging calculator to make it work:
import java.util.Scanner;
public class Test {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
int total = 0;
int score;
int average;
int counter = 0;
while (counter >= 0){
score = input.nextInt();
total = total + score;
counter++;
}
average= total/10;
System.out.println("Your average score is "+ average);
}
}
But when I enter scores, I can keep entering infinite scores and it never averages them. It just keeps expecting another score. I know it has something to do with this line:
while (counter >= 0){
but I'm not sure what to do so it works right.
You never find a way to break out of the loop:
while (counter >= 0){
score = input.nextInt();
total = total + score;
counter++;
}
will loop 2 billion times (no I'm not exaggerating) since you don't have another way to break out.
What you probably want is to change your loop condition to this:
int score = 0;
while (score >= 0){
This will break out when a negative score is entered.
Also, you have an integer division at the end. You want to make floating-point, so change the declaration to this:
double average;
and change this line to this:
average = (double)total / 10.;
You need some way to beak out of the loop. For example, entering -1:
int score = input.nextInt();
if (score < 0) { break; }
total += score;
You also seem to have a couple of errors in the calculation of the average:
Don't always divide by 10 - use the value of counter.
Use floating point arithmetic. If you need an int, you probably want to round to nearest rather than truncate.
For example:
float average = total / (float)counter;
You have to specify the counter value, the default value is 0, so the condition in the while is always true, so you will go in an infinite loop.
while (true) {
score = input.nextInt();
if (score == 0) {
break;
}
total = total + score;
counter++;
}
Now your program will realize you're done entering scores when you enter the impossible score 0.