让信件正确地进入arraylist

时间:2014-05-15 18:20:15

标签: java arraylist

我正在制作一个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);

  }
}

2 个答案:

答案 0 :(得分:0)

您应该使用Set代替List

例如,HashSet将不允许重复,而ArrayList将会重复。

这里有一篇非常好的文章:http://www.mkyong.com/java/what-is-the-different-between-set-and-list/

答案 1 :(得分:0)

要存储已使用过的字母,请考虑使用HashSet

HashSets只会存储添加到其中的任何内容的一个副本。