-4

I am making a hangman game where if I guess the wrong letter of the word in aLetter I add 1 onto the label inCorrect, however this code is adding 1 onto inAccurate when I guess correctly aswell. How can I fix this?

public class Form extends javax.swing.JFrame {

String FindWord = "apple";
int w = 0;
}

 private void attemptSignActionPerformed(java.awt.event.ActionEvent evt) {     

    int charPos = 1;
    String letter = aLetter.getText();
    charPos = FindWord.indexOf(letter);
    myMessage.setText("position is " + charPos);
    if (charPos == 0) Char0.setText(letter);
    if (charPos == 1) Char1.setText(letter);
    if (charPos == 2) Char2.setText(letter);
    if (charPos == 3) Char3.setText(letter);
    if (charPos == 4) Char4.setText(letter);
    if (charPos == 5) Char5.setText(letter);
    charPos = FindWord.indexOf(letter, charPos + 1);
    if (charPos == 0) Char0.setText(letter);
    if (charPos == 1) Char1.setText(letter);
    if (charPos == 2) Char2.setText(letter);
    if (charPos == 3) Char3.setText(letter);
    if (charPos == 4) Char4.setText(letter);
    if (charPos == 5) Char5.setText(letter);

Below is the part that i'm having trouble with

   if (charPos == -1) {

        w++;

        inCorrect.setText(Integer.toString(w));

      }

}

I want to only add 1 onto inCorrect when the letter I guess is not in the word "apple".

Raedwald
  • 46,613
  • 43
  • 151
  • 237
Vestel
  • 51
  • 1
  • 2
  • 6
  • For your interest: [a java implementation of hangman in very few lines](http://stackoverflow.com/a/22269413/256196) – Bohemian Dec 08 '14 at 03:38

1 Answers1

0

When you call

charPos = FindWord.indexOf(letter, charPos + 1);

you are setting charPos back to -1 in the case where the letter only occurs once, not twice. You need to get rid of this.

Either

  • use a different variable for the second position of the letter, OR
  • write this into a loop, to allow for any number of occurrences of the letter, OR
  • or set a boolean variable to indicate whether the letter was found; and use that to determine whether to add one to incorrect.
Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110