0

When I call my getUserInput and enter a 2d Char array that I made using my createBoard method it prints "That input was invalid! Please enter another.". I then enter another/or same value and I get an IllegalArgumentException.

However if I use the exact same code and call it on a 2d array that I made and initialized in the method, like so:

public static void main(String[] args) {
    char a = ' ';
    char b = 'x';
    char c = 'o';

    char[][] n = {{a,a,a},
                  {a,b,b},
                  {a,a,a}};

    displayBoard(n);
    getUserMove(n);
    displayBoard(n);
}

The code works perfectly. Please help I can't find my issue :/ I've included the createBoard and getUserMove methods below. Thanks!

public static char[][] createBoard(int n) {     
    char[][] charArray = new char[n][n];

    for(int i = 0; i < charArray.length; i++) {
        for (int v = 0; v < i; v++) {
            charArray[i][v] = ' ';
        }
    }
    return charArray;
}

public static void getUserMove(char[][] n) {
    Scanner in = new Scanner(System.in);
    Scanner in2 = new Scanner(System.in);

    int row = in.nextInt();
    int col = in.nextInt();

    do {
        if (row < n.length && col < n[0].length && n[row][col] == 32) {
            writeOnBoard(n, 'x', row, col);
        }

        else {
            System.out.println("That input was invalid! Please enter another.");
            if (! in2.hasNextInt()) {
                in2.next();
            }
            row = in2.nextInt();
            col = in2.nextInt();

            writeOnBoard(n, 'x', row, col);
        }

    }while(row > n.length - 1 || col > n[0].length - 1);
}
1
  • 1
    Why is your inner loop only going up to i instead of to the length of the inner array? Commented Nov 8, 2017 at 20:44

1 Answer 1

1

This for loop is broken:

for(int i = 0; i < charArray.length; i++) {
    for (int v = 0; v < i; v++) {
        charArray[i][v] = ' ';
    }
}

First iteration, lets look at the code from the top. In your first for loop you initialize i as 0, but then in second for loop you initialize v as 0 as well and check if v < i. This is not right.

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

Comments

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.