How to fix getting an average from user input - java

The instructions are the following:
Write a method called inputThenPrintSumAndAverage that does not have any parameters.
The method should not return anything (void) and it needs to keep reading int numbers from the keyboard.
When the user enters something that is not an int then it needs to print a message in the format "SUM = XX AVG = YY". XX represents the sum of all entered numbers of type int.
YY represents the calculated average of all numbers of type long.
I've coded the following method but I keep getting the incorrect average. What can I change to get the correct average?
public static void inputThenPrintSumAndAverage(){
Scanner scanner = new Scanner(System.in);
int sum = 0, counter = 0;
long average = 0L;
while(true) {
boolean number = scanner.hasNextInt();
if(!number)
{
counter++;
break;
}
else {
int digit = scanner.nextInt();
sum += digit;
counter++;
}
}
average = sum / counter;
System.out.println("SUM = " + sum + " AVG = " + average);
}

The following should do:
if(!number)
break;
Your average is wrong because you are incrementing "counter" more than you should.
Of course in the end you are going to have to add one more if statement to make sure you are not attempting to divide by counter if the counter is zero. In that case, an average is undefined.
Also, as others have pointed out in the comments, it is entirely unclear to us what you mean when you say "I keep getting the incorrect average", and we generally frown upon questions worded so vaguely. But if by any chance a "correct average" for you means an average with decimals, then you should use a double instead of a long for your average, and you should cast your counter to double before dividing, so as to force a double division instead of a long division.

Use scanner.hasNextInt() to read util a non-integer value is supplied as input:
public static void inputThenPrintSumAndAverage() {
Scanner scanner = new Scanner(System.in);
int number, sum = 0, counter = 0;
long average = 0L;
while (scanner.hasNextInt()) {
number = scanner.nextInt();
sum += number;
counter++;
}
if(counter != 0){
average = sum / counter;
}
System.out.println("SUM = " + sum + " AVG = " + average);
}
Note that you should check the value of counter to avoid a division by zero.
If you want the average to be in decimals, change the type of average to double: double average; and cast the division to double: average = (double) sum / counter;.

Related

Close list with variables with the fixed number -1

I am very new to coding and Java. I have the following assignment: Write a program that reads a couple of positive numbers from the input and computes and prints the average, with 3 decimals precision. The input list closes with the number -1.
So I have a working program, however I have no clue how to integrate the condition 'print the average with 3 decimals precision'. Do you have any idea how to fix this? Many thanks!
See my code below:
import java.util.Scanner;
public class Parta {
public static void main(String[] args){
Scanner numInput = new Scanner(System.in);
double avg = 0.0;
double count = 0.0;
double sum = 0.0;
System.out.println("Enter a series of numbers. Enter -1 to quit.");
while (numInput.hasNextDouble())
{
double negNum = numInput.nextDouble();
if (negNum == -1)
{
System.out.println("You entered " + count + " numbers averaging " + avg + ".");
break;
}
else
{
sum += negNum;
count++;
avg = sum/count;
}
}
}
}
You just have to break out of the loop for your -1 condition.
while(1) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
if(n == -1)
break;
}
Change
for(int i=0; i < numbers.length + 1= -1 ; i++)
to
for(int i=0; i < n ; i++)
The
%n
is out of place in the print statement also. I'd remove that.
To implement your -1 condition, check for a == -1 in the for loop:
if (a == -1) {break;}
The input list closes with the number -1.
I assume this means that -1 is the final number you are looking for and when read then all inputs are then completed? You just need a condition to check if the number you are looking at is -1, if it is then stop reading.
Your code does not meet your requirements.
The first requirement is that you have to calculate fractions. But you stick to int as type of your variables. As written by #nbokmans your variables should be of type double or float.
The other problem is that your code takes the first number given as the count of the numbers to follow. But you're told to use any number for calculation until input is -1. You cannot do this with a for loop, you need a while loop for this.
An the easiest way to accomplish your task is to calculate the result on the fly while getting the input:
pseudo code:
declare sum as double initially 0.0;
while(input is not -1)
sum = (sum + input) / 2;
output sum:

Incorrect variable value for during average calculation for num 1 to 100

public class SumandAverage {
public static void main(String[] args) {
int sum=0;
double average;
int lowerBound = 1;
int upperBound = 100;
while(lowerBound<=upperBound) {
sum = sum+lowerBound;
lowerBound++;
}
System.out.println("The Sum is "+sum);
average=sum/upperBound;
System.out.println("The average is " + average);
}
}
the result i get is "The Sum is 5050 The average is 50.0"..why is my upperBound changing to 101 and resulting in incorrect average value of 50.0 instead of 50.5 when i am not even changing it at all? must be something silly, but i am not able to spot.
You are dividing ints, so the result is int. Divide doubles instead :
average=(double)sum/upperBound;
5050/100 = 50, since int division can only produce an int. After you assign it to a double variable, you get 50.0.
int sum=0;
double average;
int lowerBound = 1;
int upperBound = 100;
while(lowerBound<=upperBound) {
sum = sum+lowerBound;
lowerBound++;
}
System.out.println("The Sum is "+sum);
average=(double)sum/upperBound; //change
System.out.println("The average is " + average);
ie change only average=(double)sum/upperBound; .In your case you are getting int results because sum and upperBound are int.Other option is you can also change the datatypes of these variable to get the desired output.
Demo

Java sum of numbers error

This code seems to run well, but am getting error message regarding calculating the sum of the integers entered.
The point of the exercise is to input a series of numbers, and after the value -1 is entered, calculate the sum of the numbers, how many numbers were entered, the mean value, and the number of odd and even numbers.
The output I get suggests the program is running fine, but still get an eror message.
With input 1 17 2 18 17 -1 should print "sum: 55" expected:<55> but was: <0>
Apologies in advance if my Java syntax is a bit inelegant. I'm fairly new at this! Code below.
import java.util.Scanner;
public class LoopsEndingRemembering {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Type numbers: ");
int n;
double sum = 0.0;
int i = 0;
double average = 0.0;
int odd = 0;
int even = 0;
while (true) {
n = Integer.parseInt(reader.nextLine());
if (n != -1) {
System.out.print("Type numbers: ");
sum += n;
i++;
average = sum / i;
if (n % 2 == 0) {
even++;
} else {
odd++;
}
} else {
System.out.println("Thank you and see you later!");
System.out.println("The sum is " + sum);
System.out.println("How many numbers: " + i);
System.out.println("Average: " + average);
System.out.println("Even numbers: " + even);
System.out.println("Odd numbers: " + odd);
break;
}
}
}
}
You're printing 55.0. It seems you're getting this program tested by another program which you don't have access to the source code of.
Issue 1
You probably want to print 55 specifically.
Instead of:
double sum = 0.0;
Do:
int sum = 0;
Issue 2
Use int over double. Cast to double for the average value.
Then instead of this:
average = sum / i;
Do something like:
average = (double)sum / i;
Issue 3
Also, it seems the error message wants you to print as sum: 55.
So change this:
System.out.println("The sum is " + sum);
To:
System.out.println("sum: " + sum);

Java Array, int reset to 0?

Working on a project where the user input determines the size of an array. Afterwards the user inputs values and receives the sum. Finally the program shows the user the percentage of each value to the total. For example if the array size is 4 and a[0] = 2, a[1] = 1, a[2] = 1, and a[3] = 2 it will show "2, which is 33.333% of the sum" "1, which is 16.666% of the sum" etc. The problem I have is that after the array and sum are determined and I try to find the percentage I get 0. Is the sum reset to 0 since it's a different for loop?
import java.util.Scanner;
public class CountIntegersPerLine
{
public static void main(String[] args)
{
int elements;
int arraySize;
int sum = 0;
int percentage;
System.out.println("How many numbers will you enter?");
Scanner keyboard = new Scanner(System.in);
//Length of array is determined by user input
arraySize = keyboard.nextInt();
int[] array = new int[arraySize];
System.out.println("Enter 4 integers, one per line");
for (elements = 0; elements < arraySize; elements++)
{
//Gather user input for elements and add the total value with each iteration
array[elements] = keyboard.nextInt();
sum = sum + array[elements];
}
System.out.println("The sum is " + sum);
System.out.println("The numbers are:");
for (elements = 0; elements < arraySize; elements++)
{
//Display the percent that each value contributes to the total
percentage = array[elements] / sum;
System.out.println(array[elements] + ", which is " + percentage + " of the sum.");
}
System.out.println();
}
}
Integer division will result in a zero value when the numerator is less than the denominator. You should declare percentage as a float or a double.
int percentage;
...
...
...
percentage = array[elements] / sum;
and you will need to cast the division operation in your case to preserve the value:
percentage = (double)array[elements] / sum;
Try declaring the sum variable as a double (or float):
double sum = 0.0;
Why? because in this line:
percentage = array[elements] / sum;
... You're performing a division between two integers, and all the decimals will be lost. You can verify that this is indeed the case, for example try this:
System.out.println(1/3); // it'll print 0 on the console
The solution to this problem is to have either one of the division's operands as a decimal number, by declaring as such their types (as I did above) or by performing a cast. Alternatively, this would work without changing sum's type:
percentage = array[elements] / ((double)sum);

for loop structure

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

Categories

Resources