为什么indexof不工作?

时间:2014-01-27 02:02:34

标签: java string char indexof

我有一个刽子手游戏的程序,索引对我不起作用?它在第30行。我一直想弄明白但我不能。如果(guessedWord.indexOf(letter)> = 0)。我将继续努力找出我做错了什么

import java.io.PrintStream;
import java.util.Scanner;

public class Hangman
{
public static void main(String[] args)
{
String[] words = { "write", "program", "that", "receive", "positive" };

Scanner input = new Scanner(System.in);
char anotherGame;
do
{
int index = (int)(Math.random() * words.length);

String hiddenWord = words[index];
StringBuilder guessedWord = new StringBuilder();

for (int i = 0; i < hiddenWord.length(); i++) {
guessedWord.append('*');
}
int numberOfCorrectLettersGuessed = 0; int numberOfMisses = 0;

while (numberOfCorrectLettersGuessed < hiddenWord.length()) {
System.out.print("(Guess) Enter a letter in word " + guessedWord +
" > ");
String s = input.nextLine();
char letter = s.charAt(0);

if (guessedWord.indexOf(letter) >= 0) {
System.out.println("\t" + letter + " is already in the word");
} else if (hiddenWord.indexOf(letter) < 0) {
System.out.println("\t" + letter + " is not in the word");
numberOfMisses++;
} else {
int k = hiddenWord.indexOf(letter);
while (k >= 0) {
guessedWord.setCharAt(k, letter);
numberOfCorrectLettersGuessed++;
k = hiddenWord.indexOf(letter, k + 1);
}
}
}

System.out.println("The word is " + hiddenWord + ". You missed " + numberOfMisses +         (numberOfMisses <= 1 ? " time" : " times"));

System.out.print("Do you want to guess for another word? Enter y or n> ");
anotherGame = input.nextLine().charAt(0);
}while (anotherGame == 'y');
}
}

3 个答案:

答案 0 :(得分:1)

您传递的是char,预计会String。尝试使用String.valueOf(letter),如下所示:

if (guessedWord.indexOf(String.valueOf(letter)) >= 0) {

// Your code

}

答案 1 :(得分:1)

StringBuilder#indexOf(char)未定义。你可以做到

if (guessedWord.indexOf(Character.toString(letter)) >= 0) {

答案 2 :(得分:0)

StringBuilder没有indexOf(char)方法。

guessedWord.indexOf(letter)

应该是

if (guessedWord.toString().indexOf(letter) >= 0) {