Random generated array does not print small value correctly

Rahman

New Member
#1
My code is not working because it is always printing small value as 0. Thanks in advance for your help.
Mã:
public class Tests {

    public static void main(String [] args){
        int [] num=new int[10];
        Random random= new Random();
        //1st time both big and small value will be at 0
        int big=num[0];
        int small=num[0];

        for(int i=0;i<num.length;i++){

            num[i]=random.nextInt(10);
            System.out.print(num[i] +" ");

            if(num[i]>big){
                big=num[i];             
            }   
            if(num[i]<small){
                small=num[i];
            }
        }
        System.out.println();
        System.out.println("Big " + big);
        System.out.println("Small " + small);
    }
}
See below the issue: Good Result:

5 1 1 3 8 3 5 1 1 0 Big 8 Small 0

Bad Result: 6 8 8 1 7 5 2 6 8 4 Big 8 Small 0
 

Admin

Administrator
Thành viên BQT
#2
This is because small is 0 and every random value will be generated between 0 and 10, so 0 is the smallest.

To fix it, change to

Mã:
int small = Integer.MAX_VALUE;
 

Từ khóa phổ biến

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.

Top