Clarke Woogner
Clarke Woogner

Reputation: 113

Java random number between two variables. Positive and Negative numbers needed

I am trying to get random points in a rectangle based off of the y min and max and the x upper bound and lower bound which are all stored in int variables.

I have followed several suggestions on stackoverflow including the answer listed here: How to get random number with negative number in range?

which is to use this formula: int number = random.nextInt(max - min) + min;

But when I implement in my own code I only get positive values still

        System.out.println("y Maximum: " + ymax);
        System.out.println("y Minimum: " + ymin);
        System.out.println("x Upper Bound: " + xupperb);
        System.out.println("x Lower Bount: " + xlowerb);

        for (int i = 0; i <= 10; i++) {
            xp = rd.nextInt(((xupperb) - (xlowerb)) + (xlowerb));
            yp = rd.nextInt((ymax + 1) - (ymin - 1) + ymin);

            System.out.println("Iteration: " + i);
            System.out.println("xp: " + xp);
            System.out.println("yp: " + yp);

            if (xp > maxxp) {
                System.out.println("\tNew Max xp: " + xp);
            }
            if (xp < minxp) {
                System.out.println("\tNew Min xp: " + xp);
            }
            if (yp > maxyp) {
                System.out.println("\tNew Max yp: " + yp);
            }
            if (yp < minyp) {
                System.out.println("\tNew Max yp: " + yp);
            }
      }
y Maximum: 1011
y Minimum: -528
x Upper Bound: 10
x Lower Bount: -10
Iteration: 0
xp: 2
yp: 180
    New Max xp: 2
    New Max yp: 180
Iteration: 1
xp: 1
yp: 588
    New Max xp: 1
    New Max yp: 588
Iteration: 2
xp: 7
yp: 30
    New Max xp: 7
    New Max yp: 30
Iteration: 3
xp: 9
yp: 392
    New Max xp: 9
    New Max yp: 392
Iteration: 4
xp: 6
yp: 436
    New Max xp: 6
    New Max yp: 436
Iteration: 5
xp: 1
yp: 179
    New Max xp: 1
    New Max yp: 179
Iteration: 6
xp: 6
yp: 599
    New Max xp: 6
    New Max yp: 599
Iteration: 7
xp: 2
yp: 623
    New Max xp: 2
    New Max yp: 623
Iteration: 8
xp: 6
yp: 560
    New Max xp: 6
    New Max yp: 560
Iteration: 9
xp: 6
yp: 130
    New Max xp: 6
    New Max yp: 130
Iteration: 10
xp: 7
yp: 627
    New Max xp: 7
    New Max yp: 627

Any help would be greatly appreciated!

Upvotes: 0

Views: 205

Answers (2)

collapsar
collapsar

Reputation: 17238

The parentheses in your code are placed incorrectly. The following matches your intentions:

xp = rd.nextInt(xupperb) - xlowerb) + xlowerb;
yp = rd.nextInt((ymax + 1) - (ymin - 1)) + ymin; // or ... '+ (ymin -1)' ?

The yp values will start at ymin, not ymin - 1, which might not be what you want

Upvotes: 2

iluxa
iluxa

Reputation: 6969

xp = rd.nextInt(((xupperb) - (xlowerb)) + (xlowerb));

should become

xp = rd.nextInt(xupperb - xlowerb) + xlowerb;

Upvotes: 1

Related Questions