Exact division (whole)

3

I need to make a division but it always gives zero rest, exact division. I think I'm sinning in the condition.

Random Number;
int Rnumber1;
int Rnumber2;
RandomValor1 = (TextView) findViewById(R.id.TxtValor1);
RandomValor2 = (TextView) findViewById(R.id.TxtValor2);

Number = new Random();
Rnumber1 = Number.nextInt(20);
Rnumber2 = Number.nextInt(10);


while (Rnumber1/Rnumber2==0 ) {

    Rnumber1 = Number.nextInt(20);
    Rnumber2 = Number.nextInt(10);


}

RandomValor1.setText(Integer.toString(Rnumber1));
RandomValor2.setText(Integer.toString(Rnumber2));
    
asked by anonymous 04.10.2016 / 15:40

1 answer

5

To get the rest of the division of two numbers use the modulo % operator. See the following code:

while(valor1 % valor2 != 0) 

The above condition means that while the rest of the division of valor1 by valor2 is non-zero, do something.

Adapt to your code:

while (Rnumber1 % Rnumber2 != 0) {

    Rnumber1 = Number.nextInt(20);
    Rnumber2 = Number.nextInt(10);
}

To ensure that Rnumber1 is greater than or equal to Rnumber2 changes the condition as follows:

while (Rnumber1 < Rnumber2 || Rnumber1 % Rnumber2 != 0) {

    Rnumber1 = Number.nextInt(20);
    Rnumber2 = Number.nextInt(10);
}

From what I understand, you have the following requirements:

  • The divisor must be a number between 1 and 10
  • Dividend must be a number the divisor.
  • The Number.nextInt(x) method generates numbers between 0 and x-1 , so to ensure the first requirement the code will look like this:

    Rnumber2 = Number.nextInt(10) + 1;
    

    To ensure the following requirement we will do this:

    R.number1 = Number.nextInt(21 - Rnumber2) + Rnumber2;
    

    The changed code will look like this:

    Random Number;
    int Rnumber1;
    int Rnumber2;
    
    Number = new Random();
    RandomValor1 = (TextView) findViewById(R.id.TxtValor1);
    RandomValor2 = (TextView) findViewById(R.id.TxtValor2);
    
    do {
        Rnumber2 = Number.nextInt(10) + 1;
        Rnumber1 = Number.nextInt(20 - Rnumber2 + 1) + Rnumber2;
    }while (Rnumber1 % Rnumber2 != 0)
    
    RandomValor1.setText(Integer.toString(Rnumber1));
    RandomValor2.setText(Integer.toString(Rnumber2));
    
        
    04.10.2016 / 15:48