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

Each Letter i type in gets a hit even if its wrong

public class Hangman {

  public static void main(String[] args) {
    // Your incredible code goes here...
    Game game = new Game ("Treehouse");

   Prompter prompter = new Prompter(game);
    boolean isHit = prompter.promptForGuess();
    if(isHit){
      System.out.println("Yeah a Hit");
    } else {
      System.out.println("Noipe!!!!");   
    }
  }
}


import java.util.Scanner;

class Prompter{
  private Game game;

  public Prompter (Game game){
     this.game = game;
  }

public boolean promptForGuess(){
  Scanner scanner = new Scanner(System.in);
  System.out.print("Enter a Letter:  ");
  String guessIm = scanner.nextLine();
  char guess = guessIm.charAt(0);
  return game.applyGuess(guess);
  }
}

class Game{
  private String Ans;
  private String hits;
  private String misses;

   public Game(String Ans){
     this.Ans = Ans;
     hits = "";
     misses = "";
   }

  public boolean applyGuess(char letter){
  boolean isHit = Ans.indexOf(letter) !=1;
  if (isHit){
    hits += letter;
  }
  else{
     misses += letter;
  }
  return isHit;
  }
}

1 Answer

i believe the error lies in the Game class, inside the applyGuess() method, check this line : boolean isHit = Ans.indexOf(letter) !=1;

it should be != - 1; !

Thank You it Worked