Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Java Objects Delivering the MVP Exceptions

Chris Rubio
Chris Rubio
1,643 Points

I dont understand how the following sysntax checks if a letter has been guesses already or not,please explain:

public boolean applyGuess(char letter){
    if(misses.indexOf(letter) != -1 || hits.indexOf(letter) != -1){
      throw new IllegalArgumentException(letter + "has already been guesses);
                                         }

2 Answers

Alright Chris, lets see.

public boolean applyGuess(char letter) { 
    if( misses.indexOf(letter) != -1 || hits.indexOf(letter) != -1) { 
        throw new IllegalArgumentException(letter + "has already been guesses);
        }
}

Couple of things first:

  • indexOf() function checks for the argument in the array. If its present in the array, it returns its index otherwise returns -1.

  • Here misses and hits must be arrays that contains the letters that had been guessed already. If letter is present in the word it goes to hits otherwise it goes into misses.

About the code:

we check if the passed letter is there in misses array or hits array, if yes, then throw an argument that letter has been already guessed.

Just for future reference, use 3-backtics for adding your code. enclose your code in 3-backtics. Use the markdown cheatsheet. Cheers!!!

Sean M
Sean M
7,344 Points

I'm trying to understand this myself. My thoughts are:

-1 is returned if the letter is not present within the array.

Therefore, if the letter guessed does not equal -1 in either the hits or misses array, that means the letter guessed is already present.