简体   繁体   中英

How to generate two random integers in java

I am trying to create a code that gives me two random int. They should be even, not zero and the reminder of x/z should be zero. This is the code i tried but sometimes y==0 anyway. Something simple missing?

            public static void main(String[] args){

        int x;
        int y=0;

        Random test = new Random();

        do{
        x = test.nextInt((10)+1) *2;
        }while(x == 0);

        try{
        do{
        y=test.nextInt(10);
        }while(x%y != 0 && y == 0);
        }catch(ArithmeticException e){

        }


        System.out.println(x);
        System.out.println(y);

}

instead of looping and searching two numbers that match, you could also create numbers that always have the properties you need:

  • X must be Y*[integer number]
  • both X and Y must be even

The first property can be achieved by generating a random Y (>0) and a random_factor (>0). X is set to the product of Y*random_factor.

The second property can be achieved by multiplying both X and Y with 2.

y=0 is possible, because your while(x%y != 0 && y == 0); means "while x%y is not zero AND y is zero". If x%y = 0 y can be anything and the loop will break. Change it to logical OR.

while(x%y != 0 || y == 0);

Replace your first loop from

do{
   x = test.nextInt((10)+1) *2;
}while(x == 0);

with

do{
   x = test.nextInt((10)+1) *2;
}while(x == 0 || x%2 != 0);

This will make sure that 'x' is even and non-zero.

(2) Get rid of your try-catch block. It's not needed. Replace it

with a simple do-while loop.

do{
   y=test.nextInt(10);
}while(y == 0 || y%2 != 0 || x%y != 0);

This will make sure y is even and non-zero as well as y is an integral factor of x.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM