[英]Need guidance on a simple pig game that terminates and ends
我正在尝试创建一个简单的Pig游戏。我遇到的问题是程序终止。 例如,当我运行它时,输入两个球员和两个名字可以正常工作,并且第一轮也是如此。.一旦我输入n,然后轮到球员2,程序就停止了..我希望继续直到得分达到..
下面是我的代码..我将不胜感激..我完全迷失了这个..是的...我是一个初学者..
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;
public class PigGame {
public static void main(String[] args) {
ArrayList<Player> users = initialize();
for (Player p : users) {
System.out.println(p.getNick() + "'s turn!");
System.out.println("Your score is: " + p.getScoreTotal() + "!");
takeTurn(p);
if (p.getScoreTotal() >= 100) {
System.out.println(p.getNick() + "wins! Congratulations");
return;
}
}
}
private static ArrayList<Player> initialize() {
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to Pig!");
System.out.println("How many will play the game?");
int qusers = sc.nextInt();
sc.nextLine();
ArrayList<Player> users = new ArrayList();
for (int i = 1; i <= qusers; i++)
{
System.out.println("Enter the name of player " + i + ":");
users.add(new Player(sc.nextLine(), 1, 6));
}
return users;
}
private static void takeTurn(Player p) {
String input = "";
int currentScore = 0;
Scanner sc = new Scanner(System.in);
do {
p.rollDice();
currentScore += p.getDieWorth();
System.out.println(p.getNick() + "'s dice rolled " + p.getDieWorth());
if (p.getDieWorth() != 1) {
System.out.println("Your score is: " + currentScore + " for this round.");
System.out.println("Do you want to roll again? (j/n)");
input = sc.nextLine();
} else {
System.out.println("Sorry");
currentScore = 0;
}
}
while ((input.equals("j")) && (p.getDieWorth() != 1));
p.increaseScore(currentScore);
}
}
这是您的代码。
for (Player p : users) {
System.out.println(p.getNick() + "'s turn!");
System.out.println("Your score is: " + p.getScoreTotal() + "!");
takeTurn(p);
if (p.getScoreTotal() >= 100) {
System.out.println(p.getNick() + "wins! Congratulations");
return;
}
}
这仅通过用户一次。 for
要遍历每个用户,然后完成。 您需要一个while循环。
//this is somewhat messy, but it gets the point across
Player p = users.get(0);
int playerIndex = users.size();
while(p.getScoreTotal() < 100) {
if(playerIndex == users.size()) {
playerIndex = 0;
}
p = users.get(playerIndex);
playerIndex++;
System.out.println(p.getNick() + "'s turn!");
System.out.println("Your score is: " + p.getScoreTotal() + "!");
takeTurn(p);
}
System.out.println(p.getNick() + "wins! Congratulations");
return;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.