gpt4 book ai didi

java - 如何防止掷骰子的重复语句

转载 作者:行者123 更新时间:2023-12-01 12:01:33 24 4
gpt4 key购买 nike

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

输出应该如下所示:

Enter Seed: 100

rolls: 6 6 2

You rolled a pair

rolls: 6 6 1

You rolled a pair

You are lucky

我不确定如何移动 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com