Java Dice Roll程序(Craps Game)没有获得输出

时间:2017-10-26 22:39:06

标签: java

我是stackoverflow和java的新手。我目前正在制作一款名为Craps的骰子滚动程序游戏,我很难找到错误。

while

当我运行代码时,它会询问我想要播放多少轮,虽然它会跳过整个过程并跳转到System.out.print("Error. Please try again.");循环并打印{{1}}

2 个答案:

答案 0 :(得分:1)

由于你是在主要的循环中调用它 - 你的else案例应该更简单:

public static Random rand = new Random(); //INITIALIZE RANDOM
public static Scanner in = new Scanner(System.in); //INITIALIZE USER INPUT
public static int numOfDice = 2; //INITIALIZE NUMBER OF DICES INVOLVED
public static int numOfSides = 6; //INITIALIZE NUMBER OF SIDES INVOLVED

public static int roll() { //ROLL DICE
    int dice1 = rand.nextInt(numOfDice + (numOfSides+1));//ROLL DICE 1
    int dice2 = rand.nextInt(numOfDice+(numOfSides+1)); //ROLL DICE 2
    int roll = dice1 + dice2; //STORE THE VALUE OF THE TWO DICES
    return roll;
}

public static void round() {
    int firstPoint = roll(); //CHECK THE VALUE OF THE FIRST ROLL
    if (firstPoint == 7 || firstPoint == 11) { //IF THE VALUE IS EITHER 7 OR 11 IN THE FIRST ROLL YOU WIN
        System.out.println("You win!");
    } else if (firstPoint == 2 || firstPoint == 3 || firstPoint == 12) { //IF THE VALUE IS EITHER 2 3 OR 12 IN THE FIRST ROLL YOU LOSE
        System.out.println("You lose!");
    } else {
        System.out.println("you tied!");
    }
}

public static void main(String[] args) {
    System.out.println("How many rounds would you like to play?");
    int amtRound = in.nextInt();
    for (int i=1; i<=amtRound; i++) {
        round();
    }
}

此外,您可以在声明时初始化变量,并且您不需要round()来返回任何值,因为您无论如何都不会对其进行任何操作。

示例输出:

How many rounds would you like to play?
7
you tied!
you tied!
you tied!
you tied!
you tied!
You win!
You lose!

实现它的另一种方法是将amtRound传递给round并让它计算出它应该在循环中运行多少次(迭代地):

public static void round(int times) {
    while (times > 0) {
        int firstPoint = roll(); //CHECK THE VALUE OF THE FIRST ROLL
        if (firstPoint == 7 || firstPoint == 11) { //IF THE VALUE IS EITHER 7 OR 11 IN THE FIRST ROLL YOU WIN
            System.out.println("You win!");
        } else if (firstPoint == 2 || firstPoint == 3 || firstPoint == 12) { //IF THE VALUE IS EITHER 2 3 OR 12 IN THE FIRST ROLL YOU LOSE
            System.out.println("You lose!");
        } else {
            System.out.println("you tied!");
        }
        times--;
    }
}

public static void main(String[] args) {
    System.out.println("How many rounds would you like to play?");
    int amtRound = in.nextInt();
    round(amtRound);
}

答案 1 :(得分:1)

while循环已锁定

既然你永远不会改变secPhase,它永远不会停止。您可能希望在循环中的某处执行类似secPhase = roll();的操作。

另外,你不应该int secPhase = firstPoint; secPhase = 0;。只需int secPhase = 0;

另外,我认为您甚至不需要while循环开始。