Java,while-loop,计数器不会退出循环

时间:2015-11-24 16:06:45

标签: java while-loop counter

我几乎是Java的初学者,我无法弄清楚以下问题。我希望这段代码生成0-2之间的随机数(工作正常)并将其添加到int A,B,C,D,直到A + B + C + D的总和达到4.我试图解决这个问题有一个柜台(称为' zaehler')。当计数器达到4时,while循环不会停止!我真的无法弄明白 - 也许有人有一些建议吗?提前谢谢!

public void levelUp()
{
    int zaehler = 0; 
    Random randomGenerator = new Random();
    int A = 0;
    int B = 0;
    int C = 0;
    int D = 0;
    while(zaehler <= 4)
    {
        int randomInt1 = randomGenerator.nextInt(3); 
        A += randomInt1;
        zaehler = zaehler + randomInt1;

        System.out.println("randomInt1 = " + randomInt1);
        System.out.println("A = " + A);
        System.out.println("Zaehler = " + zaehler);

        int randomInt2 = randomGenerator.nextInt(3);
        B += randomInt2;
        zaehler = zaehler + randomInt2;

        System.out.println("randomInt2 = " + randomInt2);
        System.out.println("B = " + B);
        System.out.println("Zaehler = " + zaehler);

        int randomInt3 = randomGenerator.nextInt(3);
        C += randomInt3;
        zaehler = zaehler + randomInt3;

        System.out.println("randomInt3 = " + randomInt3);
        System.out.println("C = " + C);
        System.out.println("Zaehler =" + zaehler);

        int randomInt4 = randomGenerator.nextInt(3);
        D += randomInt4;
        zaehler = zaehler + randomInt4;

        System.out.println("randomInt4 = " + randomInt4);
        System.out.println("D = " + D);
        System.out.println("Zaehler = " + zaehler);
    }    
}   

public static void main (String [] args)
{
    TestRandom test = new TestRandom();
    test.levelUp(); 
}   

2 个答案:

答案 0 :(得分:0)

使用for循环。如果你想按照你的意愿停止循环,你可以在自己的控制下,比它更好。

for (int i=0;i<=4;i++){
//Enter your loop here
//To create a random between 0 and 2:
int random= 0+(int)(Math.random()*2));
}

我不知道你是否理解了循环,这会创建一个名为i的int(就像你的zaehler),每次循环结束时都会增加1。此循环将持续到int i达到4。

答案 1 :(得分:0)

这将停留在4或5.如果你根本不想要5,那么你需要更新你的问题如何处理这种情况。

public void levelUp()
{
    int zaehler = 0;
    Random randomGenerator = new Random();
    int A = 0;
    int B = 0;
    int C = 0;
    int D = 0;
    while (zaehler <= 4)
    {
        int randomInt1 = randomGenerator.nextInt(3);
        A += randomInt1;
        zaehler = zaehler + randomInt1;

        if (zaehler >= 4)
            break;

        int randomInt2 = randomGenerator.nextInt(3);
        B += randomInt2;
        zaehler = zaehler + randomInt2;

        if (zaehler >= 4)
            break;

        int randomInt3 = randomGenerator.nextInt(3);
        C += randomInt3;
        zaehler = zaehler + randomInt3;

        if (zaehler >= 4)
            break;

        int randomInt4 = randomGenerator.nextInt(3);
        D += randomInt4;
        zaehler = zaehler + randomInt4;

        if (zaehler >= 4)
            break;
    }

    System.out.println("A = " + A);
    System.out.println("B = " + B);
    System.out.println("C = " + C);
    System.out.println("D = " + D);

    System.out.println(zaehler);
}