Sean Sean - 1 month ago 5
Android Question

Finding out min, max, avg, sum in ArrayList

Im writing a program to get three numbers from user and put it into an array list and find the sum, avg, min, and max. Im having problems with finding the min. When i run the code the Min is always zero. How do i fix this problem?

int num = 0;
int sum = 0;
int avg = 0;
int min = 0;
int max = 0;
int i = 0;

ArrayList<Integer> array = new ArrayList<Integer> ();

Scanner input = new Scanner (System.in);

for (i = 0; i < 3; ++i){

System.out.println("Enter a number");
num = input.nextInt();
array.add(num);

sum += num;

if(num > max){
max = num;
}

if(num < min){
min = num;
}

}

avg = sum / i;

System.out.println("Sum: " + sum);
System.out.println("Avg: " + avg);
System.out.println("Max: " + max);
System.out.println("Min: " + min);



//Code Result

//Enter a number
// 10
//Enter a number
// 20
//Enter a number
// 30

//Sum: 60
//Avg: 20
//Max: 30
//Min: 0 <-- this is always zero

}

Answer

that's because you set min to be 0 and it is lower than all values. you need to initialize it to a large number (say Integer.MAX_VALUE) then it will work

Comments