Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have been working on my hangman program for far to long and cannot figure out why it is not replacing the characters entered with the asterisks.

There are a lot of details I have not added so please do not sit here and judge that. I need someone to tell my why the character the user enters is not replacing the asterisks and If you know what I could do to fix it please tell me.

I'm struggling. I have edited my program to show you where I know the logic error is coming from however I do not know what the error is.

  String hiddenWord = wordList[rand];
  char[] asterisks = new char[MAXCHAR];

  hideWord(hiddenWord);
  System.out.println(Arrays.toString(hideWord(hiddenWord)));
  numGuess( hiddenWord,asterisks);

  public static char[] hideWord(String hiddenWord)
  {        
      int wordLength = hiddenWord.length();
      //int length = wordLength * 2;
      char[] asterisks = new char[wordLength];

      for(int i=0; i < wordLength; i++)
      {
          asterisks[i] = '*';
      }
      return asterisks;       
  }

  public static void numGuess(String hiddenWord,char[] asterisks)
  {
      Scanner keyboard = new Scanner(System.in);
      hideWord(hiddenWord);
      int remAttempts = MAXGUESS;

      int i = 0;
      while(i < (hiddenWord.length()-1))
      {
          System.out.println("Enter a letter or 9 to quit");
          char guess = keyboard.next().charAt(i);
          if(asterisks[i] == (hiddenWord.charAt(i)))
          {
              //attemtps == hiddenWord.charAt(i);
              System.out.println("Nice job!");
              remAttempts--;
          }
          i++;
      }
  }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.0k views
Welcome To Ask or Share your Answers For Others

1 Answer

Look at this code (I changed the formatting a bit):

while (i < hiddenWord.length() - 1) {
    System.out.println("Enter a letter or 9 to quit");
    char guess = keyboard.next().charAt(i);
    //...
    i++;
}

You're asking for a letter, but you really request a String with at least the size + 1 that equals i: keyboard.next().charAt(i);. Therefore, if you write just a letter, then you'll get an Exception at the second iteration of that loop.

I guess what you meant was: keyboard.next().charAt(0);. This will return the first character of the given String.

If this doesn't solve the problem, then provide the whole Stacktrace and mark the line in your code, where the Exception occurs.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...