-1

I am typing a typical game in console now. But I have a mistake about loops. How can I use continue keyword in for loop in while loop? I want to use it for while loop.

    *****while (true) {
        System.out.print("Please type a number(It must be in between 0-"+width2+") to define the row : ");
        int x = input.nextInt();
        while (x<1 || x>width) {
            System.out.print("Please type a avaliable number to define the row : ");
            x = input.nextInt();
        }

        System.out.print("Please type a number(It must be in between 0-"+length2+") to define the column : ");
        int y = input.nextInt();
        while (y<1 || y>length) {
            System.out.print("Please type a avaliable number to define the column : ");
            y = input.nextInt();
        }
        System.out.println();
        
        int value = 10*x + y;
        
        
        
        
        for (int i = 0; i < x * y; i++) {
            if (value == array[i]) {
                System.out.println("Please type different values from beforehands.");
                continue;
            }
        }
        
        array[counter] = value;
        System.out.println("array["+counter+"] = "+array[counter]);
        counter++;
        if (gamingArea[x-1][y-1] == 0) {
            point+=10;
            continue;
        }else {
            System.out.println("GAME OVER! Your point is "+point+".");
            break;
        }
        
    }*****

1 Answer 1

0

You can label the while statement and specify it in the continue statement.

L: while (true) {
    // A
    for (int i = 0; i < x * y; i++) {
        if (value == array[i]) {
            System.out.println("Please type different values from beforehands.");
            continue L;
        }
    }
    // 
}

You can also write without continue like this.

while (true) {
    // A 
    if (IntStream.range(0, x * y).anyMatch(i -> i == value)) {
        System.out.println("Please type different values from beforehands.");
    } else {
        // B
    }
}

You can simply remove the second continue statement in your code.

Sign up to request clarification or add additional context in comments.

1 Comment

This method is used like using of goto? If it is that, can you type a code without goto for this game?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.