jeudi 19 octobre 2017

Issue with "Math.random()" in Java

I want to write a code that draws some specific points on a window. I have 3 different points $(e1,e11), (e2,e22), (e3,e33)$. I want to randomly choose one of them and depending on the output, draw a different point.

public class ChaosGame {

public static void main(String[] args) {
    Window window = new Window("Chaos", 800, 800);
    window.open();

    int e1 = 420;
    int e11 = 170;
    int e2 = 230;
    int e22 = 670;
    int e3 = 700;
    int e33 = 540;

    while (window.isOpen()) {// ändere den Fensterinhalt
        int pos1 = 100;
        int pos2 = 300;

        int i = (int) (Math.random() * 3);

        if (i == 0 || i == 3) {
            window.fillRect(pos1 + e1 / 2, pos2 + e11 / 2, 5, 5);
            pos1 = e1 / 2;
            pos2 = e11 / 2;
            window.refresh();
        } else if (i == 1) {

            window.fillRect(pos1 + e2 / 2, pos2 + e22 / 2, 5, 5);
            pos1 = e2 / 2;
            pos2 = e22 / 2;
            window.refresh();
        } else {

            window.fillRect(pos1 + e2 / 2, pos2 + e22 / 2, 5, 5);
            pos1 = e3 / 2;
            pos2 = e33 / 2;
            window.refresh();

        }
    }

}

}

fillRect draws my points in the new window. Now when I run this program, only two points appear, even though it should go on "while window.isOpen" so until I close the window. I think something with my Math.random() might be wrong.

Aucun commentaire:

Enregistrer un commentaire