Reputation: 9
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);
}
}
Upvotes: 0
Views: 59
Reputation: 318
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.
Upvotes: 0
Reputation: 1229
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;
Upvotes: 0
Reputation: 393851
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.
Upvotes: 1