I have been assigned a task to create a average calculator, unfortunately each time a average is done I get either one too many which doesn't fix the issue when I do number -- OR, the average is completely off.
import java.util.*;
public class Mean
{
public static void main()
{
Scanner inputLine = new Scanner(System.in);
int total = 0, number, counter = 0;
double average;
System.out.println ("Enter your numbers, press 0 to launch");
while (inputLine.nextInt() != 0)
{
number = inputLine.nextInt();
if(number >= 1)
{
total = total + number;
counter++;
}
}
average = total/counter-1;
System.out.println ("Your Average is : " + average);
}
}
You are reading an int from the Scanner twice per loop. The while loop reads an int to make sure it's not 0, but then the body of the while loop reads a second int and only counts that second int.
Assign the result of the first nextInt call to a variable in the while loop condition, and use that variable in the body for the calculations.
You are subtracting 1 from your average calculation. There's no reason for that. Don't do it.
You are performing Java's integer division, which will truncate any decimals. Cast one of the operands to / to double to force floating-point calculations.
while ( (number = inputLine.nextInt() ) != 0)
{
if(number >= 1)
{
total = total + number;
counter++;
}
}
average = (double) total / counter;
You may want to add code for a condition where the user entered no items, to prevent dividing by 0.
Related
Instructions;
Statistics are often calculated with varying amounts of input data. Write a program that takes any number of non-negative integers as input, and outputs the max and average. A negative integer ends the input and is not included in the statistics. Assume the input contains at least one non-negative integer.
Output the average with two digits after the decimal point followed by a newline, which can be achieved as follows:
System.out.printf("%.2f\n", average);
Ex: When the input is:
15 20 0 3 -1
the output is:
20 9.50
I have tried a few different ways to convert the int avg into a string but somehow keep messing up.. What am I not doing?? Example code below
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner (System.in);
int num = 0;
int count = 0;
int max = 0;
int total = 0;
int avg = 0;
String s=Integer.toString(avg);
do {
total += num;
num = scnr.nextInt();
count = ++count;
if (num >= max) {
max = num;
}
} while (num >= 0);
avg = total/(count-1);
System.out.printf("%.2f\n", avg);
}
}
What you are trying to do is almost correct. The only things, you would need to change for this to work are these:
int avg = 0; // The type of avg should be a float
The reason for this is that what you're printing is a float but before these changes, you are providing it with an int.
// The number you are providing avg with should be cast to a float value
avg = total/(count-1);
This is because if you didn't, you would have integer division.
// It would look like this
float avg = 0;
avg = (float)total/(count-1);
So i was calculating e(third row in picture) with numerical methods.
I was increasing the number of elements i used every iteration. And when i executed the program, floating point variable behaved in a way i didn't understand. Here is the program and the result.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int factorial = 1;
int counter = 0;
int iterationNumber;
double total = 0;
int tempCounter;
System.out.print("Enter iteration number: ");
iterationNumber = input.nextInt();
while (counter <= iterationNumber) {
tempCounter = counter;
while ((tempCounter - 1) > 0) {
factorial *= tempCounter;
tempCounter--;
}
total += ((double)1 / factorial);
System.out.println(total);
factorial = 1;
counter ++;
}
}
}
So my question is why does the value of e starts to decrease after a while instead of increasing? I want to learn how floating point variable behaves during this program and the logic behind it.
Another question is why does it start to say infinity?
n! quickly exceeds Integer.MAX_VALUE and overflows to a negative number. You are then adding a negative number to your total --- thus the decrease.
You can use BigDecimal for your calcualtions. It is slower, but will do the job.
Hey guys I need help with this assignment. When I run what I have it just loops forever, help would be much appreciated. Here's what my assignment is:
Write a program segment on the following page which reads a sequence of integers from the keyboard until 0 (zero) is entered. As it is entered print each integer (except for the 0 that stops the program) and at the average of the integers entered.
Each non-zero integer is printed on a separate line.
this continues until a zero is read, at which point the segment stops.
Here's what I have so far:
import java.util.Scanner;
public class List {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int boom = 0;
int sum = 0;
double average = 0;
int count = 0;
System.out.println("Enter a nonzero integer, please!");
boom = keyboard.nextInt();
while (boom != 0) {
sum += boom;
count++;
average = ((double) sum) / count;
System.out.println("The average is " + average);
}
}
}
You read the keyboard input only once. That's what you should do:
while (boom=keyboard.nextInt() != 0) {
sum += boom;
count++;
average = ((double)sum) / count;
System.out.println ("The average is " + average);
}
It will loop forever if you enter a non-zero integer at the boom=keyboard.nextInt() stage. The reason why is that boom never changes in your while block and the condition for stopping is that boom does not equal zero.
You'll need to set boom to a non-zero value outside of the loop and move your assignment to boom of the int from the keyboard inside the loop.
I am writing a program that reads a sequence of positive integers input by the user. User will only enter one integer at a time.Then it will compute the average of those integers. The program will end when user enters 0. (0 is not counted in the average).The program will print out the average once the program ends.
Question: My code stops working when I gets to the while loop hence it doesn't compute the input by user, hence prints out nothing. Why doesn't my while loop compute the average from the user's inputs? Appreciate your guidance :)
import java.util.Scanner;
public class AverageOfIntegers {
public static void main(String[] args) {
int integer;
double sum;
sum = 0;
double average;
Scanner input = new Scanner(System.in);
int count; count = 0;
average = 0;
System.out.println("Please enter an integer: ");
integer = input.nextInt();
while (integer != 0) {
count = count + 1;
sum = sum + integer;
average = sum / count;
}
System.out.println("Average = " + average);
}
}
This is because you are never actually summing over more than one integer. The user only ever enters one number. As a result your loop is essentially acting on just the one number. You need to put the input inside the while loop and save a running sum and count there. Something more like this
while (integer != 0) {
count += 1;
sum += integer;
average = sum / count;
integer = input.nextInt();
}
Explanation
First of all, when you define data types, you can set their default value in the definition. Ex:
double sum = 0;
vs
double sum;
sum = 0;
Secondly, sum = sum + integer; is the same as: sum += integer;
Thirdly, count = count + 1; is the same as: count += 1 OR (and better yet), count++;
As for your actual algorithm, there is one problem and one suggestion:
you are not changing integer's value after each loop. So, you can
either do that in the while condition: while ((integer =
input.nextInt()) != 0) { or, at the end of each loop:
while (integer != 0) {
count ++;
sum += integer;
average = sum / count;
integer = input.nextInt();
}
This is a suggestion for technically better code (in my opinion), but it looks better, is more intuitive and requires less calculations to calculate the average after the while loop is done instead of during. That way, you only calculate it once, where needed, vs. every loop, which is not needed.
________________________________________________________________________________
The Code (complete class)
public class AverageOfIntegers {
public static void main(String[] args) {
int integer;
double sum = 0;
double average = 0;
Scanner input = new Scanner(System.in);
int count = 0;
System.out.println("Please enter an integer: ");
// set integer = to the nextInt() while looping so it calculates properly
while ((integer = input.nextInt()) != 0) {
count ++;
sum += integer;
}
average = sum / count; // calculate the average after the while-loop
System.out.println("Average = " + average);
}
}
________________________________________________________________________________
Example input/output:
Please enter an integer:
5
10
15
0
Average = 10.0
So it did 5 + 10 + 15 = 30 (which is the sum), and then the average is 30 / 3 (30 is the sum, 3 is the count), and that gave you Average = 10.0.
You need to move integer = input.nextInt(); inside the loop, so your program will collect inputs in a loop. See the corrected version:
import java.util.Scanner;
public class AverageOfIntegers {
public static void main(String[] args) {
int integer = 0, count = 0;
double sum = 0.0, average = 0.0;
Scanner input = new Scanner(System.in);
System.out.println("Please enter an integer: ");
integer = input.nextInt();
while (integer != 0) {
count = count + 1;
sum = sum + integer;
System.out.println("Please enter an integer: ");
integer = input.nextInt();
}
average = sum / count;
System.out.println("Average = " + average);
}
}
The problem is that the input.nextInt() should be part of the loop. The way you wrote it, the code gooes into an infinite loop whenever the first input is non-zero. Instead, do:
while ((integer = input.nextInt()) != 0) {
count = count + 1;
sum = sum + integer;
average = sum / count;
}
In the loop:
while (integer != 0) {
count = count + 1;
sum = sum + integer;
average = sum / count;
}
This will only stops when integer is 0, but this variable is not changing in the loop, so it will never be 0 if it wasn't already in the first place.
According to what you said you want to do, you should probably repeat the call to integer = input.nextInt(); inside your loop, lke this:
System.out.println("Please enter an integer: ");
integer = input.nextInt();
while (integer != 0) {
count = count + 1;
sum = sum + integer;
System.out.println("Please enter an integer: ");
integer = input.nextInt();
}
average = sum / count;
Also, as others have said, you only need to compute the average once after the loop, so I moved it too.
This question already has answers here:
How do I get this code to stop input when the sum exceeds 100 and still preform the sum and average?
(2 answers)
Closed 9 years ago.
Yes, I know there are a lot of methods here. It's part of the assignment. In this code everything works as intended except that when numbers are entered that equal sum<=100, the "average" output is wrong. For example: if I put in 8,10,19 and zero to exit the output is count 3 sum 37 average 9.25.... the average should be 12.3333. Now, if i enter in 8, 10, 99 the output is count 3 sum 117 and average 39 which is correct. Why is it working for sum>100 but not sum<=100??? I don't get it. What am I missing?
public static void main(String[] args) {
//Use Main Method for gathering input
float input = 1;
// Declare variable for sum
float theSum = 0;
// Declare variable for average
float average = 0;
// Declare variable for counting the number of user inputs
int counter = 0;
/* Initialize the while loop using an input of 0 as a sentinel value
* to exit the loop*/
while (input != 0) {
if (input!=0){
counter++;
}
input = Float.parseFloat(
JOptionPane.showInputDialog(
null, "Please enter a number. Enter 0 to quit: "));
// Invoke sum method and pass input and summation to sum method
theSum = (sum(input, theSum));
if (theSum > 100)
{
JOptionPane.showMessageDialog(null, "The sum of your numbers "
+ "are greater than 100!");
break;
}
}
// Invoke display method and pass summation, average, and counter variables to it
average = (avg(theSum, counter));
display(theSum, average, counter);
}
public static float sum(float num1, float sum) {
//Add the user's input number to the sum variable
sum += num1;
//Return value of sum variable as new summation variable
return sum;
}
public static float avg(float num1, float num2) {
//Declare and initialize variable for average
//Calculate average
float average = num1 / num2;
//Return value of average variable
return average;
}
public static void display(float sum, float average, int counter) {
/* I am subtracting 1 from variable counter so as not to include the sentinel value
* of 0 that the user had to enter to exit the input loop in the overall count*/
// Display the count, sum, and average to the user
if (sum > 100) {
JOptionPane.showMessageDialog(null, "Count = " + (counter) + ", Sum = " + sum + ", Average = " + average);
}
if (sum <= 100) {
JOptionPane.showMessageDialog(null, "Count = " + (counter - 1) + ", Sum = " + sum + ", Average = " + average);
}
}
}
The reason is that you're exiting the while loop in different ways depending on the total sum. If the sum is less than 100, even when you enter the number 0 to "exit", you're still going through the loop an extra time. To be honest, the entire loop needs to be completely restructured; a do...while loop would be much easier to read and debug.
The issue is because of the way you exit the while loop as mentioned by #chrylis. So in case where the sum is <= 100 the counter is 1 larger. But when you print it you get correct result because you update the counter value here:
if (sum <= 100) {
JOptionPane.showMessageDialog(null, "Count = " + (counter - 1) + ", Sum = " + sum + ", Average = " + average);
}
As you see in your example:
"if I put in 8,10,19 and zero to exit the output is count 3 sum 37 average 9.25"
it is because the counter value is 4 (so the avg will be 37/4 = 9.25), but while displaying the result you subtract counter by 1, therefore you get the count as 3.
The do-while loop will solve the issue as the condition would be checked at the last thus the loop will exit in same manner for both <=100 and '>100`.
The do-while loop would be like this:
do{
//here goes your code
}while (input != 0);
Your counter is 1 larger than necessary. Dividing by (counter - 1) would fix it.