我正在尝试找出一种方法来防止语句打印太多次。

输出应该看起来像这样:


输入种子数:100

卷数:6 6 2

你对了

卷数:6 6 1

你对了

你很幸运


我不确定如何遍历boolean方法或仅调用boolean结果,以免多次打印出滚动类型。

import java.util.Scanner;
import java.util.Random;

public class Triple {

    public static boolean rollType(int x, int y, int z){

        boolean lucky = false;

        if(x == y && y == z){
            System.out.println("You rolled a triple");
            lucky = true;
        }
        else if(x == y || y == z || x == z){
            System.out.println("You rolled a pair");
            lucky = true;
        }
        else{
            System.out.println("You rolled nothing");
            lucky = false;
        }

        return lucky;
    }

    public static void main (String[] args) {

       Scanner scnr = new Scanner(System.in);
       Random randGen = new Random();  // New random number generator
       int seedVal = 0;
       final int MAX_DICE = 8;

        //User input
       System.out.println("Enter Seed: ");
       seedVal = scnr.nextInt();
       randGen.setSeed(seedVal);

       int a1 = (randGen.nextInt(MAX_DICE)+1);
       int b1 = (randGen.nextInt(MAX_DICE)+1);
       int c1 = (randGen.nextInt(MAX_DICE)+1);

       int a2 = (randGen.nextInt(MAX_DICE)+1);
       int b2 = (randGen.nextInt(MAX_DICE)+1);
       int c2 = (randGen.nextInt(MAX_DICE)+1);

        // randGen.nextInt(MAX_DICE) yields 0, 1, 2, 3, 4, 5, or 7
        // so + 1 makes that 1, 2, 3, 4, 5, 6, 7, or 8
        System.out.println("rolls: " + a1 + " " + b1 + " " + c1);
        rollType(a1, b1, c1);
        System.out.println("rolls: " + a2 + " " + b2 + " " + c2);
        rollType(a2, b2, c2);

        if (rollType(a1, b1, c1) && rollType(a2, b2, c2)){  //work on how to fix it from printing twice THEN the boolean. should only print boolean.
            System.out.println("You are lucky");
        }
        else{
            System.out.println("You are NOT lucky");
        }

        return;
   }
}

最佳答案

删除rollType(a1, b1, c1);之前的行rollType(a2, b2, c2);if。由于您的if方法无论如何都调用它们,因此它们是重复的。

这应该可以完全解决您的问题:现在您只有两次调用rollType函数,因此只有两组输出

更新:由于您需要特定的订单,因此此修复程序将解决您的问题。将boolean添加到您的rollType函数中,如下所示:

public static boolean rollType(int x, int y, int z, boolean print) {
    boolean lucky = false;
    if (x == y && y == z) {
        if (print) System.out.println("You rolled a triple");
        lucky = true;
    } else if (x == y || y == z || x == z) {
        if (print) System.out.println("You rolled a pair");
        lucky = true;
    } else {
        if (print) System.out.println("You rolled nothing");
        lucky = false;
    }
    return lucky;
}


然后,第一次使用rollType(a1, b1, c1, true)rollType(a2, b2, c2, true),第二次使用rollType(a1, b1, c1, false)rollType(a2, b2, c2, false)

关于java - 如何防止掷骰子重复语句,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27955036/

10-09 03:31