0

如何查看字符串数组的元素是否包含某个字母?我需要它来做刽子手。使用的单词数组是 Words。continueGame() 是我放这个的地方。我想我可以得到我的随机词,然后找出这个字母是否在那个随机词中。我怎么做?

  public void continueGame(){
    letterSelected = JOptionPane.showInputDialog(null, "Take another guess!");

        if(getWords().indexOf(getWords()) == (letterSelected)){

        }

        if(! getWords().contains(letterSelected)){
         guesses++;
         continueGame();
        }else{
           System.out.println(letterSelected);
        }
    checkBodyParts();
    JOptionPane.showInputDialog(null, "");
}
#
/**Get the random word from the array*/
public String getWords (){
    String randomWord = words[randy.nextInt( words.length)];
    return randomWord;
}



/**Get the indexes of the letter of the random word indices don't start with 1*/
public String getSelected(){
    return letterSelected;
}

/**Finds index of the letter of randomWord*/
public int getIndex(){
    int index = getWords().indexOf(getSelected());
    return index;
}
4

2 回答 2

0

I don't really understand the snippet you gave us.

But you can consider the following code to find word of an Array that contains a specified character :

String[] words = {"foo", "bar", "qux"};
for (String word : words)
{
    if (word.indexOf('a') != -1)
    {
        System.out.println("Matched word '" + word + "' for character 'a'");
    }
}
于 2013-01-12T16:14:47.883 回答
0

I just don't get your logic. You are returning new random word everytime you call getWords(). You should assign randomly generated word to some variable and then work with this variable.

To your concrete problem it should be something like this:

// get your random word
String myGeneratedRandomWord = getWords ();

// your method 
public void continueGame(){
   letterSelected = JOptionPane.showInputDialog(null, "Take another guess!");
   if(myGeneratedRandomWord.indexOf(letterSelected ) != -1) {
        // it contains the letter
   }
   else {
        // wrong guess
   }
}

Read more about String.indexOf() method.

于 2013-01-12T16:14:50.687 回答