Alex
Alex

Reputation: 3

Fill two-dimensional array with Chars from String Input

I'm making a basic game of Tic Tac Toe, accepting player input in the form of a string (i.e. a2). The first char is made into an int called row depending on the letter, the same being said for the second char into col (for array grid[row][col]). I have a block of code that throws a custom exception in the event that the first char isn't a, b, or c, and if the second char isn't 1, 2, or 3:

if(input == null) {
        throw new NullInputException();
    }
    else if(input.length() != 2) {
        throw new InvalidInputException();
    }
    else if(!(input.substring(0,1).equalsIgnoreCase("a") &&
            input.substring(0,1).equalsIgnoreCase("b") &&
            input.substring(0,1).equalsIgnoreCase("c") ||
            input.substring(1).equals("1") &&
            input.substring(1).equals("2") &&
            input.substring(1).equals("3"))) {
        throw new InvalidInputException();
    }

The problem is, this code throws an error even when the input is valid, and I don't know why. I've tried using .charAt() as opposed to .substring(), as well as messed around with my conditional statements. My question is: How do I fix this so that it accepts valid input?

Other questions that just don't help: fill two dimensional array with parts of a string; fill a 2d array with chars of 2 string

Upvotes: 0

Views: 195

Answers (2)

vojta
vojta

Reputation: 5651

You AND two conditions:

input.substring(0,1).equalsIgnoreCase("a") &&
            input.substring(0,1).equalsIgnoreCase("b")

Both cannot be true in the same time. That is why the result is always false and an exception is thrown.

What you really want is:

String first = input.substring(0,1);
String second = input.substring(1);
    if (!((first.equalsIgnoreCase("a") ||
                first.equalsIgnoreCase("b") ||
                first.equalsIgnoreCase("c")) && 
                (second.equals("1") ||
                second.equals("2") ||
                second.equals("3"))) {
        throw new InvalidInputException();
    }

Small edit for Neil...

Upvotes: 1

Neil Masson
Neil Masson

Reputation: 2689

Sometimes it is better to write a series of simpler tests which are easier to read and verify

row = input.substring(0,1).toUpperCase();
col = input.substring(1);
boolean validRow = (row.equals("A") ||
                    row.equals("B") ||
                    row.equals("C"));
boolean validCol =
        (col.equals("1") ||
        col.equals("2") ||
        col.equals("3"));

if(!(validRow && validCol)) {

Upvotes: 3

Related Questions