简体   繁体   中英

Break do while loop when output condition is met

I want to print 2 random values, such as "1, 3" so long as the two numbers printed are not equal.

The loop should break when the 2 numbers that print are the same.

I have created the following piece of code, but I am unsure as to what the condition would be in order to break the statement when the 2 numbers that output are the same. Can someone please help out? Thank you!

    Random random = new Random();

    do
    {                              
        int randomInt = random.nextInt(6);
        int randomInt2 = random.nextInt(6);
        System.out.println(Integer.toString(randomInt) + ", " + Integer.toString(randomInt2));
    }
    while ( /* problem */);

It would just be while(randomInt!=randomInt2) . And, as was said in the comments, you should declare the variables outside of the loop. You don't have to initialize them - just say

int randomInt,randomInt2;

and that will be enough.

Do this:

int randomInt, randomInt2;

do {
    randomInt = random.nextInt(6);
    randomInt2 = random.nextInt(6);
    System.out.println(randomInt + ", " + randomInt2);
} while (randomInt != randomInt2);

To clear up one of your confusions:

int i; // declaration
i = 2; // assignment
int i = 2; // declaration _and_ assignment

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM