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);
See more on this question at Stackoverflow