0

I'm writing a text based game where movement is dictated by typing "go left," "go right," etc. I have a Boolean Array List with the valid commands, and I want to compare what the user types to the members in the array. The code I have rejects all commands as invalid. I believe it's because I'm returning false, but I'm not sure how to fix it. I'm very new to this, so any and all help is appreciated.

  private boolean validCommand() {

    ArrayList<Boolean> validCommand = new ArrayList<>();
    validCommand.add(Boolean.valueOf("go left"));
    validCommand.add(Boolean.valueOf("go right"));
    validCommand.add(Boolean.valueOf("go straight"));
    validCommand.add(Boolean.valueOf("go back"));

    for (boolean checkCommand : validCommand) {
        if (typeCommand.getText().toString().equals(checkCommand))
            return true;
    }
    return false;
}

typeCommand is just the EditText the user types their command in.

2 Answers 2

1

you don't have to use ArrayList<Boolean>. you have to use ArrayList<String>. Because you want to compare String to String.

private boolean validCommand() {

    List<String> validCommand = new ArrayList<>();
    validCommand.add("go left");
    validCommand.add("go right");
    validCommand.add("go straight");
    validCommand.add("go back");

    // List#contains() will return true if List contains arg, or false not.
    return validCommand.contains(typeCommand.getText().toString());
}
Sign up to request clarification or add additional context in comments.

2 Comments

That worked. Thanks a bunch! I had a similar statement earlier, only I used validCommand.equals(...) instead of .contains. I thought maybe a Boolean array list would be better, but I was overthinking it.
yep!! enjoy coding!! :)
0

Boolean.valueOf(String s) returns the boolean value of the string, ie "true" would return true. If you have random string, like "go left", it will return false. So if validity is your concern, I would change the array to an array of strings instead and compare the array string with what was typed. If the comparison returns true then you have a valid command.

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.