0
    for (i=1; i < 9; i++) {
        for (j=1; j < 9; j++) {
            if ( board[i][j] == "o" ) {
                j = j-1;

                if ( board[i][j] == "x" ) {
                    do {
                        j--;
                    }
                    while (board[i][j] != "-");
                    board[i][j] = ".";
                }
            }
        }
    }

I have this piece of code as part of a method, there are two versions, one as written above and one where j = j-1 is replaced with j = j+1 and j-- is replaced with j++

The positive version works perfectly fine but if I put in the negative version, the code compiles fine but when I attempt to run it nothing happens, the console just hangs and I have to close and reopen it. Can anyone tell me what I am doing wrong? Thanks in advance.

edit:

for (i=1; i < 9; i++) {
        for (j=1; j < 9; j++) {
            if ( board[i][j].equals("o") ) {
                j = j-1;

                if ( board[i][j].equals("x") ) {
                    do {
                        j--;
                    }
                    while (!board[i][j].equals("-"));
                    board[i][j] = ".";
                }
            }
        }
    }

I have edited the code as indicated but the problem persists

29
  • 3
    Look at this again if ( board[i][j] == "o" ) Commented Feb 14, 2016 at 21:55
  • 1
    Your code as-is is incorrect. And this is probably related to comparing Strings. You need to fix this and debug. Commented Feb 14, 2016 at 22:05
  • 1
    You also have a trailing ; here while (!board[i][j].equals("-"));. I suggest you restart and try to make a minimal reproducible example. Please read How to Ask. Commented Feb 14, 2016 at 22:16
  • 1
    @Tunaki - do while loops have trailing semi colons Commented Feb 14, 2016 at 22:22
  • 2
    Thanks cricket_007 MCEmperor and RichardTingle this was the problem, very silly mistake on my part thanks for the help Commented Feb 14, 2016 at 22:32

1 Answer 1

1

Your logic is wrong. You're never changing the square that contains "x", so you keep encountering it, so you keep decrementing j, so you will encounter it again next time, so ...

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

1 Comment

you're right I was attempting to find the space next to the one with the "x" but didn't realise i was creating the infinite loop by using the same variables in my a for loop and my while loop. Thanks

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.