How to make a minimum ceiling and a maximum ceiling in a random number? [duplicate]

1

I'm developing an application in Java and in my controller I have a function that generates the random numbers. Example:

In my first column I want you to manage from 0 to 8, until then OK.

In the second column I want to generate 9 to 17, in this case I can not do it because I can not determine which number x will start, because by default it counts with the beginning of 0.

That is, I want you to generate 0 to 9, then 9 to 17, then 18 to 25, and so on ...

Here is my code below:

public void grupoDeSete(){
        Random random = new Random();

        /*=====ACTIVITY PLUS=======*/
        int generated1_plus = random.nextInt(9);
        int generated2_plus = random.nextInt(17 - 9) + 10;
        int generated3_plus = random.nextInt(24 - 18) + 20;

        /*Grupo de 7 números*/
        String sevenGroup = String.valueOf(generated1_plus
                + " - "
                + generated2_plus
                + " - "
                + generated3_plus);

        //Resultado
        setSecond(sevenGroup);
    }


    public String getSecond() {
        return second;
    }

    public void setSecond(String second) {
        this.second = second;
    }

How can I do this?

    
asked by anonymous 17.12.2017 / 20:55

2 answers

3

You can do something like this:

public class Sorteio {
    private static final Random RND = new Random();

    public static int sortear(int min, int max) {
        return RND.nextInt(max - min + 1) + min;
    }

    public static int[] sortearSete() {
        return new int[] {
            sortear(0, 9),
            sortear(10, 18),
            sortear(19, 26),
            sortear(27, 33),
            sortear(34, 39),
            sortear(40, 44),
            sortear(45, 48)
        };
    }
}

The sortear(int, int) method gives you two numbers within a range. For example, sortear(20, 30) gives any number from 20 to 30, including 20 itself and 30 itself. And then the sortearSete() method gives you those 7 numbers. It is important that you adjust the numeric tracks within this method for the tracks you want.

I have placed the following tracks: a track containing 10 numbers from 0 to 9; a strip containing 9 numbers from 10 to 18; a strip containing 8 numbers from 19 to 26; a strip containing 7 numbers from 27 to 33; a track containing 6 numbers from 34 to 39; a track containing 5 numbers from 40 to 44 and a track containing 4 numbers from 45 to 48.

    
17.12.2017 / 21:24
0

You should call nextFloat or nextDouble , which return decimals between zero and one and do the transformations you need. More or less as below:

(int) min + (random.nextFloat() * (max - min));

This will return an int with values between min and max.

    
17.12.2017 / 21:07