Question: program that generates 20 numbers between 1000 and 1999 and shows that leave the rest in division 5 of 11


Build a Java application to generate 20 numbers from 1000 to 1999 and show those that divided by 11 let rest 5.




To generate random numbers, we have to import the Random class, which gives methods for generating random numbers:
import java.util.Random;


Step 1: 


We need to create an object of type Random, object 'randomGenerator'.
It who will 'take care' of the generation and the types (integer, decimal, etc.).


Step 2:

A loop of 20 iterations, where we generate 20 integers.

Step 3:

The piece: randomGenerator.nextInt(1000)
Generates random numbers within a range of 1000 numbers from 0 to 999.
Because we want to generate numbers between 1000 to 1999, we must add 1000, getting:
randomGenerator.nextInt(1000) + 1000

Step 4:


We will use the operator '%' (modulus or remainder of the division) and a conditional 'if' to print only those numbers that leave remainder 5 when divided by 11.

The Java code is:


import java.util.Random;

public class random1 {
    public static void main(String[] args) {

        // Step 1: Preparing the generator
        Random randomGenerator = new Random();
        
        // Step 2: Generating 20 numbers
        for(int count=1 ; count <= 20 ; count++){
        
        // Step 3: generating a number between 1000 and 1999
            int random_num = randomGenerator.nextInt(1000) + 1000;
            
        // Step 4: printing only those who let rest 5 in the division by 11
            if(random_num % 11 == 5)
                System.out.println(random_num);
        }
    }

}


Second manner:

We declare full only once, and 'feed' the generator to each iteration.
The Java Code is:


import java.util.Random;

public class random2 {
    public static void main(String[] args) {
        int random_num;
        
        // Step 1: Generating 20 numbers
        for(int count=1 ; count <= 20 ; count++){
            
        // Step 2: Preparing the generator
            Random randomGenerator = new Random();
        
        // Step 3: generating a number between 1000 and 1999
            random_num = randomGenerator.nextInt(1000) + 1000;
            
        // Step 4: printing only those who let rest 5 in the division by 11
            if(random_num % 11 == 5)
                System.out.println(random_num);
        }
    }

}

No comments: