我正在制作一个Hangman游戏,需要一些帮助来跟踪已经猜到的字母。我正在使用一个arraylist来跟踪使用的字母。我需要一些帮助才能让它正常工作。这是我的代码:
for(int i=0; i < word.length(); i++)
{
if(letter.equals(word.substring(i, i+1)))
{
//What happens if it does equal the letter
newWord = newWord + letter + " ";
}
else
{
//what if it is NOT the letter
newWord = newWord + "_ ";
}
}
System.out.println(newWord);
System.out.println("Misses: " + letters);
这是带有字母和字母数字的输出:
team 4 _ _ _ _ Enter a letter: t t _ _ _ Misses: [t, t, t]
我如何得到它,以便arraylist不会将“t”保存在已经使用过它的地方?
请求的完整代码:
import java.util.Scanner;
import java.io.*;
import java.util.ArrayList;
import TerminalIO.KeyboardReader;
public class Hangman
{
public static void main(String [] args)throws IOException
{
KeyboardReader reader = new KeyboardReader();
Scanner scan = new Scanner(new File("Hangman.txt"));
PrintWriter write = new PrintWriter(new File("Scorecard.txt"));
ArrayList<String> words = new ArrayList<String>();
ArrayList<String> letters = new ArrayList<String>();
int random,wordSize;
String word, letter, newWord="";
//puts words into array and gets a random work
while(scan.hasNext())
{
words.add(scan.nextLine());
}
random = (int)(Math.random() * (words.size()));
//gets the size of the random word and print number of "_" needed
word = words.get(random);
wordSize = word.length();
System.out.println(word);
System.out.println(wordSize);
for(int c = 1; c <= wordSize; c++)
System.out.print("_ ");
letter = reader.readLine("Enter a letter: ");
for(int i=0; i < word.length(); i++)
{
if(letter.equals(word.substring(i, i+1)))
{
newWord = newWord + letter + " ";
}
else
{
newWord = newWord + "_ ";
}
}
System.out.println(newWord);
System.out.println("Misses:" + letters);
}
}