打印随机字母 - LinkedList

时间:2011-12-20 19:19:48

标签: java

在这个程序中,我创建了一个LinkedList('lettersLeft'),其中我添加了Letters('Letters'是一个类)。每个字母有3个值:1)这是那个字母(即'A') ,2)它在游戏中出现的次数(即'9'),3)你得到的分数(即'1')。另外,getNextLetter()我从包里得到下一个随机字母。我想制作一个for循环,它会从包中打印出2个随机字母及其值(即“A,9,1 D,4,2”)。这是我的代码(如果你不明白的话请问)

Letters_bag

public class Letters_bag {

public static final Letters A = new Letters('a', 9, 1);
public static final Letters B = new Letters('b', 2, 3);
public static final Letters C = new Letters('c', 2, 3);
public static final Letters D = new Letters('d', 4, 2);
public static final Letters E = new Letters('e', 12, 1);
public static final Letters F = new Letters('f', 2, 4);


public static final Letters[] allLetters = new Letters[] {
    Letters_bag.A,
    Letters_bag.B,
    Letters_bag.C,
    Letters_bag.D,
    Letters_bag.E,
    Letters_bag.F,

};


LinkedList<Letters> lettersLeft = new LinkedList();


public Letters_bag() {
    // add all the letters
    addLetter(A);
    addLetter(B);
    addLetter(C);
    addLetter(D);
    addLetter(E);
    addLetter(F);

}

// helper method to add the letters
private void addLetter(Letters sl) {
    for (int i=0;i<sl.getCount();i++) {
        this.lettersLeft.add(sl);
    }
}
 /**
 *Returns the next random letter from the bag.
 */
Letters getNextLetter() {
    // shuffle those letters
    Collections.shuffle(lettersLeft);
    // return a random letter
    return lettersLeft.removeFirst();
}

}

字母

public class Letters {
private char value;
private int count;
private int points;

public Letters(char value, int count, int points) {
    this.value = value;
    this.count = count;
    this.points = points;
}

public char getValue() {
    return value;
}

public int getCount() {
    return count;
}


public int getPoints() {
    return points;
}

1 个答案:

答案 0 :(得分:1)

你的意思是?

Collections.shuffle(allLetters);
for(int i=0;i<letterCount;i++)
    System.out.println(allLetters[i]);

您的IDE可以为您生成toString方法,您可以简化它。 (或者自己写一个)