-1

I am making a game of hangman, and am wishing for the code to check if the hidden word contains any letter from the alphabet, in any position. eg charAt(0), charAt(1) etc. Once it checks if the letter is in the word, i want it to set its corresponding underlying label to that letter.

At the moment, my code is as follows:

if (SecretWord.charAt(0) == 'T') {
    Underline0.setText("T");
}
if (SecretWord.charAt(1) == 't') {
    Underline1.setText("t");
}
if (SecretWord.charAt(2) == 't') {
    Underline2.setText("t");
}
if (SecretWord.charAt(3) == 't') {
    Underline3.setText("t");
}

This does the job, but it is bulky, and it will have to be copied and pasted for all letters of the alphabet.

Unihedron
  • 10,902
  • 13
  • 62
  • 72
Bison
  • 1
  • 1

2 Answers2

2

You can create an array of Underline objects like:

Label[] underlines = new Label[secretWord.length()];

I don't know if you're using labels or text fields - you can change the Label type if needed. Then you can use a loop:

    for (int i=0; i<underlines.length; i++) {
        underlines[i] = new Label(String.valueOf(secretWord.charAt(i)));
    }

But this is really basic Java - you should grab some book or find a tutorial in the net: Books: http://www.javaworld.com/article/2076338/in-search-of-the-best-java-book-for-beginners.html http://www.coderanch.com/t/627462/java/java/book-learning-java-beginner

Tutorials:

http://www.learnjavaonline.org/ - here you have some basics.

http://docs.oracle.com/javase/tutorial/ - here you have 'official' Oracle tutorials.

And thats a quick Guoogle search.

One other thing - don't start your variable names with capital letters - it's against the convention. Capital letters are reserved for class names.

Michał Schielmann
  • 1,372
  • 8
  • 17
  • Is that an AWT Label or JavaFX Label...? – MadProgrammer Aug 17 '14 at 09:26
  • The question is what is the real type of the underline objects from the original question ;) My code will compile for awt - I didn't check the API for JavaFX label. – Michał Schielmann Aug 17 '14 at 09:31
  • While I agree that there is little or no context to the question to make a judgement call based on the information available from the user, it might be useful to highlight this, as AWT components really shouldn't be mixed with Swing...Technically correct, but I'd worried about the OP taking the example code literally and running into other problems - just saying ;) – MadProgrammer Aug 17 '14 at 09:34
1

The following can be helpful:

put lables in an array names lblArray
...
if ((SecretWord.charAt(i) >= 'a' && SecretWord.charAt(i) <= 'z') || 
    (SecretWord.charAt(i) >= 'A' && SecretWord.charAt(i) <= 'Z')) {
    lblArray[i].setText(Character.toString(SecretWord.charAt(i)));
}
...

Or you can use ascii codes of alphabet character.

HaMi
  • 539
  • 6
  • 23