I am new to Java, so I apologize if I am simply overlooking something simple. I wrote this code to make a few simple calculations, but when I run it, Java does not seem to be adding my first integer that is input when calculating the average. Everything else seems to be fine, so I would appreciate any help. Thanks.
import java.util.Scanner;
public class IntegerCalc {
public static void main(String[] args){
System.out.println("Enter a list of non-negative integers.");
System.out.println("Enter a negative number to indicate the end of your input.");
Scanner keyboard = new Scanner(System.in);
int min = keyboard.nextInt();
int max = min;
double average = 0;
double numberOfInt= 1;
int next = keyboard.nextInt();
double total = 0;
while (next > 0){
if (next > max)
max = next;
else if (next < min)
min = next;
total = total + next;
numberOfInt++;
next = keyboard.nextInt();
}
average = total/numberOfInt;
System.out.println("The largest integer is " + max);
System.out.println("The smallest integer is " + min);
System.out.println("The average is " + average);
}
}
It looks like your code does sum all the input numbers, but your numberOfInt is off by one.
You should initialize it to
double numberOfInt= 0;
instead of
double numberOfInt= 1;
You only want to increment numberOfInt when you add the current value of next to the total, so the first time you add next to total, numberOfInt should become 1.
What I can see is that inside while loop you have this condition:
if (next > max)
max = next;
else if (next < min)
min = next;
Your first value never goes to total.Your first value will count towards average is only when value of next is equal to first value.To solve this problem you can initialize total with max or min(since they are equal initially):
double total = (double) max;
your int numberOfInt should not be initialized at value 1. Since you increment it by 1 with each iteration of your loop, it's value is off by one. Instead, initialize it at value 0.
Related
this was supposed to be fairly simple, but apparently somethings wrong with my control boolean, when I input a negative number instead of ending the loop it throws an exception, any help is appreciated.
import java.util.*;
public class AverageMinMax {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
double average;
int count = 0, sum = 0, next;
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
boolean areMore = true;
System.out.println("Please enter the numbers you wish to evaluate:");
System.out.println("Followed by a negative number");
// not sure why i used a do while loop but it works i guess
do {
next = keyboard.nextInt();
sum = sum + next;
next++;
if (next < 0)
areMore = false;
} while (areMore == true);
{
sum = sum + next;
average = sum / count;
{// the minmum and max values
if (next > max)
max = next;
if (next < min)
min = next;
}
System.out.println("Your average is: " + average);
System.out.println("Your maximum number is: " + max);
System.out.println("Your minimum number is: " + min);
}
}
}
Error:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at com.test.task.AverageMinMax.main(AverageMinMax.java:29)
Your issues:
You increase next instead of count.
Outsider (sum = sum + next) is also wrong. You should not add next after loop breaks.
Min-max should be calculated inside the loop.
Some improvement suggestions:
Use while it is cleaner than do-while.
Use hasNextInt to check if it is a number or not.
If your input is a char or any special character while loop breaks.
import java.util.*;
public class AverageMinMax {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
double sum = 0, average =0;
int count = 0, next = 0;
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
System.out.println("Please enter the numbers you wish to evaluate:");
System.out.println("Followed by a char or any special character to calculate and exit");
// use while it is more cleaner.
// use hasNextInt to check if it is number or not
// if your input is a char or any special character while loop breaks
while (keyboard.hasNextInt()) {
next = keyboard.nextInt();
sum = sum + next;
// the minmum and max values
if (next > max)
max = next;
if (next < min)
min = next;
count++;
}
average = sum / count;
System.out.println("Your average is: " + average);
System.out.println("Your maximum number is: " + max);
System.out.println("Your minimum number is: " + min);
}
}
Issues
count is not incremented and its causes divide by 0 error
computation of max, min, sum, average seems incorrect
solution
Repeated read input(integer) from user
if the input is positive, add to sum, update min, update max and update count
if its negative, break the input loop
if any input is passed, then compute average
if no input is passed, then do not compute average
import java.util.Scanner;
class AverageMinMax {
public static void main(String[] args) {
final Scanner keyboard = new Scanner(System.in);
int count = 0, sum = 0, min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
System.out.println("Please enter the numbers you wish to evaluate.");
System.out.println("Followed by a negative number to stop input");
do {
final int next = keyboard.nextInt();
if (next < 0) {
break;
}
sum = sum + next;
max = Math.max(max, next);
min = Math.min(min, next);
count++;
} while (true);
if (count > 0) {
double average = (sum * 1.0) / count; // need to multiply by 1.0 to have fraction
System.out.println("Your average is: " + average);
System.out.println("Your maximum number is: " + max);
System.out.println("Your minimum number is: " + min);
} else {
System.out.print("No input to process");
}
}
}
You are getting ArithmeticException because you initialize count to 0. But after that when you are getting input from console. instead of increasing the count and doing count++. You are doing next++ in the loop.
And also getting the min max should also needs to be done in loop currently they are just in block. Although they are not responsible for your error of divide by zero.
this line is
average = sum / count;
I'm creating the program that determines the largest and smallest number is a series of numbers entered by the user. I've created several tests cases for my code and they all work out, but it fails the most simple test case. When the user inputs a single number. For instance, if the user sets the terminating value to be 25, then enters -1, and finally enters the terminating the value, the output should be
Largest: -1 and Smallest: -1. However, my code will output Largest: 0 and Smallest: -1 -- I why this happens (because I initialized the max value to be 0 before running the loop), but how can I fix this?
Here's my code...
Scanner scan = new Scanner(System.in);
// Declaration variables
double min;
double max = 0;
System.out.println("Enter terminating number: ");
double terminator = scan.nextDouble();
System.out.println("Enter a number: ");
double num = scan.nextDouble();
min = num;
if (num == terminator) {
System.out.println("There must be one number in the list.");
// break;
} else {
while (num != terminator) {
System.out.println("");
num = scan.nextDouble();
if ((num < min) && (num != terminator)) {
double temp = min;
min = num;
max = temp;
} else if ((num > min) && (num != terminator)) {
max = num;
} else {
max = min;
}
}
System.out.println("Largest: " + max);
System.out.println("Smallest: " + min);
}
Instead of initializing max = 0, do max = num just like you already do with min.
It's not clear why you're initializing max differently from min; when a single number has been entered, it's both the minimum and the maximum. Right now, the only code that modifies max is within the loop that reads numbers beyond the first, so the first number has no effect on it.
The object is to get the average of the entered values.
It is to stop when a negative number is entered.
I am trying to get the smallest and largest values entered.
The problem I am having is that my if statements will not take the smallest/largest new values entered.
It just gives me the Integer.Max_Value and Integer.Min_Value.
import java.util.Scanner;
public class LargeSmallAverage {
public static void main(String[] args) {
// TODO Auto-generated method stub
double count = 0;
double amtOfNums = 0;
int input = 0;
int smallest = Integer.MAX_VALUE, largest = Integer.MIN_VALUE;
int number;
System.out.println("Enter a series of numbers. Enter a negative number to quit.");
Scanner scan = new Scanner(System.in);
while ((input = scan.nextInt()) > 0) {
count += input;
amtOfNums++;
}
while(input>=0){
for(int counter=1; counter<amtOfNums; counter++){
number=scan.nextInt();
if(number<smallest)
smallest=number;
if(number>largest)
largest=number;
}
}
System.out.println("You entered " + amtOfNums + " numbers averaging " + (count/amtOfNums) + ".");
System.out.println("The smallest number is "+ smallest);
System.out.println("The largest number is " + largest);
}
}
Currently you have two loops. One sums the numbers, and the other finds the largest and smallest numbers. Given your output, it sounds like you should be doing it all in one loop - ideally with more useful variable names too. (Your count is actually a sum, not a count... and there's no need for it to be a double. You could make it a long if you really want to avoid overflow. Yes, you need to perform floating point arithmetic for your average, but you can do that when you take the average... your sum is logically an integer.)
int sum = 0;
int smallest = Integer.MAX_VALUE;
int largest = Integer.MIN_VALUE;
int count = 0;
while ((input = scan.nextInt()) >= 0) {
count++;
sum += input;
// Alternative: smallest = Math.min(smallest, input)
if (input < smallest) {
smallest = input;
}
// Alternative: largest = Math.max(smallest, input)
if (input > largest) {
largest = input;
}
}
// Cast for count is just to force floating point division.
System.out.println("You entered " + count +
" numbers averaging " + (sum / (double) count) + ".");
System.out.println("The smallest number is "+ smallest);
System.out.println("The largest number is " + largest);
There is a problem with your while loop condition: while(input>=0){
here input will be always less than zero due to your previous while statement:while ((input = scan.nextInt()) > 0)
Here while loop exits only when you enter a number which is less than zero.. so input will have that value..
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.
I have an assignment to find the minimum, maximum, and average of numbers that a user inputs. Basically, they type in positive integers, seperated by a space and Java scrolls through them and adds them up. I'm able to find the sum, the average, and the largest integers, however, I am unable to find the smallest. I thought the best way to figure this out would be to set the variable representing the smallest int equal to the variable representing the largest int outside of the loop. Then, within the loop, do something like this:
if(getInt < min)
{
min = getInt;
}
Where getInt is the user-inputted value and min is the minimum integer value. Every time I run this, though, min returns as 0.
Here is my full code:
import java.util.Scanner;
public class exc5
{
public static void main (String[] args)
{
System.out.println("Write a list of nonnegative integers, each seperated by a space. To signal the end of the list, write a negative integer. The negative integer will not be counted");
Scanner keyboard = new Scanner (System.in);
keyboard.useDelimiter(" |\n");
int count = 0;
int sum = 0;
int max = 0;
int min = max;
double average = 0;
boolean notNull = true;
while(notNull == true)
{
int getInt = keyboard.nextInt();
if(getInt < 0)
{
notNull = false;
}
else
{
if(getInt > max)
{
max = getInt;
}
if(getInt < min)
{
min = getInt;
}
sum += getInt;
count++;
average = (sum)/(count);
}
}
System.out.println("Sum = " + sum);
System.out.println("Average = " + average);
System.out.println("Max = " + max);
System.out.println("Minimum = " + min);
}
}
Any help is appreciated!
You should initially set min to Integer.MAX_VALUE, and max to Integer.MIN_VALUE.
You need to start with a large min, not 0 (only negative numbers are less then 0). Try this:
int min = Integer.MAX_VALUE;
This is a fairly standard pattern. Also, to be "correct", your code should also include:
int max = Integer.MIN_VALUE;
Then the full range of integer input, positive and negative, is handled.
Edit:
Another, more "classic" approach would be to use an object reference, rather than a primitive (which always has a value), so the initial state can be easily distinguished as null. In this case, using Integer, rather than int for the values would allow testing for null. If I were a university professor marking such work, I would rather see the object approach - using min/max values for primitives will work, but it's a bit of a "trick".
The code wold look like this:
Integer min;
while (...) {
if (min == null || getInt < min) {
min = getInt;
}
}
And similar for max.
This:
int max = 0;
int min = max;
initializes min to zero. (After all, max hasn't become the largest integer yet.) So this:
if(getInt < min)
will never be true. Try changing this:
int min = max;
to this:
int min = Integer.MAX_VALUE; // largest possible Java `int`
That's because you're assigning min = 0, so obviously unless you input a number lower than 0, the minimum is 0. You should initialize min to Integer.MAX_VALUE
int min = Integer.MAX_VALUE;
(
or also:
int min = 0xFFFFFFFF;
Just for hacking around :P. Use the first one! :)
)
You are setting min to zero, so (since the inputs are positive) none of the inputs are less than min.
The normal way to do this is to set the initial value of max to Integer.MIN_VALUE, and the initial value of min to Integer.MAX_VALUE.
This ensures that any input value will affect at least one of min and max - usually both!
You initialize min with 0. Try to initialize with Integer.MAX_VALUE, i.e. it would be best to do:
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
Otherwise, your check:
if(getInt < 0)
will break out of the loop and you will never go over 0.
you have min set as 0 to start with so getInt will never be less. You should set min at the beginning of the loop and that will solve your issue.
Fully working and "cleaned" version of your program:
import java.util.Scanner;
public class exc5
{
public static void main ( String [] args )
{
Scanner keyboard = new Scanner( System.in );
int count = 0;
int sum = 0;
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
double average = 0;
boolean notNull = true;
while ( notNull == true )
{
int getInt = keyboard.nextInt();
if ( getInt < 0 )
notNull = false;
else
{
if ( getInt > max )
max = getInt;
if ( getInt <= min )
min = getInt;
sum += getInt;
count++;
}
}
average = ( sum ) / ( count );
System.out.println( "Sum = " + sum );
System.out.println( "Average = " + average );
System.out.println( "Max = " + max );
System.out.println( "Minimum = " + min );
}
}