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.
Related
// 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));
}
}
}
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
thank you for your help.
Here is the assignment:
Computer Technology Instructor has a small class of 10 students. The instructor evaluates the performance of students in the class by administering 2 midterm tests and a Final Exam.
Write a program that prompts the instructor to enter the 10 grades of midterm 1 and store these numbers in an array. Next prompt for the 10 grades of midterm 2 and store these numbers in a different array. Next prompt for the 10 grades of the Final Exam and store these in a different array. Next add midterm1 to midterm2 to Final and store the totals in a different array. Next, scan the array that has the totals and identify the minimum grade and maximum grade. Inform the instructor of the minimum grade and maximum grade.
The two bold phrases are where I am having problems. Everything works except for the minimum grade and maximum grade. Here is what it tells me, after I've only entered numbers between 65 and 100:
The highest test score is: 276 The lowest test score is: 249
Here is my code:
import java.util.Scanner;
public class Arrays {
public static void main(String[] args) {
// Create a scanner
Scanner input = new Scanner(System.in);
// Prompt for the 1st mid term
int [] midTerm1 = new int[10];
int [] midTerm2 = new int[10];
int [] finalExam = new int[10];
int [] grades = new int[10];
for (int i = 0; i < midTerm1.length; i++){
System.out.println("Enter the 10 Mid Term 1 grades: ");
midTerm1[i] = input.nextInt();
}
// Prompt for the 2nd mid term
for (int i = 0; i < midTerm2.length; i++){
System.out.println("Enter the 10 Mid Term 2 grades: ");
midTerm2[i] = input.nextInt();
}
// Prompt for Final grades
for (int i = 0; i < finalExam.length; i++){
System.out.println("Please enter a Final Exam grade: ");
finalExam[i] = input.nextInt();
}
for (int i = 0; i < grades.length; i++){
grades[i] = (midTerm1[i] + midTerm2[i] + finalExam[i]);
}
int minGrade = grades[0];
int maxGrade = grades[0];
for (int i = 0; i < grades.length; i++)
{
if (minGrade > grades[i])
minGrade = grades[i];
if (maxGrade < grades[i])
maxGrade = grades[i];
}
System.out.print("The highest test score is: " + maxGrade);
System.out.print("The lowest test score is: " + minGrade);
}
}
Edit:
grades[i] = (midTerm1[i] + midTerm2[i] + finalExam[i]);
Your code may in fact be correct. Since you're adding your three test scores together, expect that the grade will be not between 65 and 100 but rather between 195 and 300.
If you want a number between 65 and 100, this needs to be divided by 3:
grades[i] = (midTerm1[i] + midTerm2[i] + finalExam[i]) / 3;
or else find some other way to normalize the grades. For instance, if the final is 50% of the grade then you could have:
grades[i] = (25 * midTerm1[i] + 25 * midTerm2[i] + 50 * finalExam[i]) / 100;
But again your current solution may in fact be the correct one.
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