-3

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);

}
Peter Turner
  • 11,199
  • 10
  • 68
  • 109
Maak
  • 3
  • 3
  • 2
    Possible duplicate of [Generating random integers in a specific range](http://stackoverflow.com/questions/363681/generating-random-integers-in-a-specific-range) – Chisko Jan 24 '17 at 21:52

3 Answers3

0

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.

Ray
  • 686
  • 3
  • 6
0

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);
Sami
  • 2,050
  • 1
  • 13
  • 25
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.

VHS
  • 9,534
  • 3
  • 19
  • 43