【发布时间】:2015-11-04 19:19:38
【问题描述】:
我正在尝试创建一个增强的猪游戏,用户可以在其中滚动用户输入的骰子数量。如果掷出的所有骰子都是一,那么您将失去您的银行积分,如果其中之一是一,您将没有积分,您的银行是安全的。否则,您可以将滚动的积分存入银行。我正在尝试遍历队列,以便每个玩家轮到他们,但它只是循环队列中的同一个人,询问玩家想要掷多少个骰子,然后得到结果并终止。我在这里做错了什么?
这也是当前的控制台输出:
import java.util.Scanner;
import java.util.stream.IntStream;
import javax.lang.model.element.Element;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;
public class EnhancedGameOfPig {
static int count;
static int roll() {
return (int) (6.0 * Math.random()) + 1;
}
public static void play() {
Scanner sc = new Scanner(System.in);
Queue<Player> myQueue = new LinkedList<Player>();
System.out.println("How many players are there? (2-10 Max)");
int numOfPlayers = sc.nextInt();
sc.nextLine();
for (int i =0; i < numOfPlayers; i++) { // creates specified number of
// players and adds
// them to a queue
System.out.println("What is your name player " + (i+1) + "?");
String playerName = sc.nextLine();
Player player = new Player(playerName, 0);
myQueue.add(player);
}
System.out.println("How many points would you like to play to, to win?"); // sets
// the
// number
// of
// points
// required
// to
// win
// the
// game
int maxPoints = sc.nextInt();
sc.nextLine();
for (Player e : myQueue) {
System.out.println("How many dice would you like to roll " + myQueue.peek().getPlayerName() + " ?");
int numofDice = sc.nextInt();
sc.nextLine();
int[] diceArray = new int[numofDice]; // creates an array to hold
// values of each dice roll
for (int i = 0; i <= numofDice-1; i++) {
diceArray[i] = roll(); // rolls dice and adds dice roll values
// to array
if (diceArray[i] == 1) {
count++;
}
}
int first = diceArray[0]; // looks at first value of array
for (int element : diceArray) {
if (element == first && first == 1) { // checks to see if all
// rolls were 1's
System.out.println("All of the dice you rolled were ones! You loose all your banked points!");
myQueue.peek().setBankedPoints(0);
break;
}
}
if (count == 1) {
System.out.println("You rolled a one, so you don't get any points. Sorry!");
} else {
int sum = IntStream.of(diceArray).sum();
System.out.println(sum + " points have been added to your bank!");
myQueue.peek().bankedPoints += sum;
}
}
}
}
【问题讨论】:
-
在你的 for-each 循环中
for(Player e : myQueue)将myQueue.peek().getPlayerName()更改为e.getPlayerName(),你的 for 循环在你的main方法完成之前正确循环一次myQueue