tasteslikejava tasteslikejava - 19 days ago 6
Java Question

Java nextInt() generates negative numbers

I am making a random line generator for fun. For some reason, the program does not make use of the maximum numbers I provided in the

nextInt().
Strangely, the only
nextInt()
that works properly is
space.

Here is my code:

public class LineFractal extends Applet {
Random rnd = new Random();
int width = 640;
int height = 640;
int x = 1000;
int endy1 = rnd.nextInt(320);
int endx1 = rnd.nextInt(320);
int starty1 = rnd.nextInt(320);
int startx1 = rnd.nextInt(320);
int space = rnd.nextInt(25);
public void init() {
setSize(width, height);
Frame c = (Frame)this.getParent().getParent();
c.setTitle("Line Generator");
}
public void paint(Graphics g) {
while (x > 0) {
x -= 1;
g.drawLine(startx1, starty1, endx1, endy1);
endy1 += space;
endx1 -= space;
}
g.drawString("Space: " + space, width-100, height-10);
g.drawString("Y (End): " + endy1, width-100, height-20);
g.drawString("Y (Start): " + starty1, width-100, height-30);
g.drawString("X (End): " + endx1, width-100, height-40);
g.drawString("X (Start): " + startx1, width-100, height-50);
}
}


Why is it doing this?

EDIT: Just ran it again, and the X (Start) and the Y (Start) do work, but the (End) integers do not. They will generate a completely random number, sometimes as low as -21842. But they are not always negative.

NPE NPE
Answer

Java nextInt() generates negative numbers

No, nextInt() -- the way you are calling it -- does not return negative numbers.

Your loop that repeatedly subtracts space from endx1 is what's causing endx1 to become negative.