为了账号安全,请及时绑定邮箱和手机立即绑定

使用一个类来随机掷骰子

使用一个类来随机掷骰子

函数式编程 2022-01-12 14:51:16
我正在编写一个骰子游戏程序,它为用户和计算机创建一个骰子,然后询问用户名、骰子的面数以及用户想在计算机上玩多少次迭代。然后让程序在每次掷骰后检查哪个掷骰更高,并在迭代结束时写回每个用户和计算机的总获胜次数以及获胜者是谁。我遇到的问题是我需要创建一个roll()类来随机化骰子并将其设置为用户滚动和计算机滚动的值,我收到此错误...Exception in thread "main" java.lang.IllegalArgumentException: bound must be positiveat java.util.Random.nextInt(Random.java:388)at classwork6_3.Die.roll(Die.java:52)at classwork6_3.ClassWork6_3.main(ClassWork6_3.java:29)这是我的main()课...package classwork6_3;import java.util.*;public class ClassWork6_3 {public static void main(String[] args) {    Scanner s = new Scanner(System.in);    Random r = new Random();    System.out.print("Enter user's name: ");    String name = s.nextLine();    int value = 0;    int value2 = 0;    System.out.print("How many sides does the die have?: ");    int sides = s.nextInt();    s.nextLine();    System.out.print("How many times would you like to roll?: ");    int numRoll = s.nextInt();    int counter = 0;    int counter2 = 0;    Die user = new Die(name, sides, value);    Die comp = new Die(value);    for(int i = 1; i<= numRoll; i++){        value = r.nextInt(user.roll(sides)) + 1;        value2 = r.nextInt(comp.roll(sides)) + 1;        System.out.printf("%s rolled: %d\n", user.getOwner(), user.getValue());        System.out.print("Computer rolled: " + comp.getValue() + "\n\n");            if(value > value2){                counter++;            } else if(value2 > value){                counter2++;            }   }            System.out.printf("%s TOTAL WINS: %d\n", user.getOwner(), counter);            System.out.print("Computer TOTAL WINS: " + counter2 + "\n\n");                if(counter > counter2){                    System.out.printf("%s wins!!\n", user.getOwner());                }else if(counter2 > counter){                    System.out.print("Computer wins\n");                }else{                    System.out.print("It's a tie!\n");                }}}
查看完整描述

2 回答

?
森栏

TA贡献1810条经验 获得超5个赞

以下是您的代码的问题:


您永远不会返回该roll(...)方法生成的随机值


public int roll(int rand){

    rand = r.nextInt(value);    

    return value;

}

将其更改为


public int roll(int rand) {         

    return r.nextInt(rand);     

}

在 for 循环中,您只需调用该roll() 方法即可。由于它已经计算出骰子的随机值,因此您无需r.nextInt()再次调用。


value = r.nextInt(user.roll(sides)) + 1;

value2 = r.nextInt(comp.roll(sides)) + 1;

将其更改为


value = user.roll(sides) + 1;

value2 = comp.roll(sides) + 1;

现在使用打印出值:


System.out.printf("%s rolled: %d\n", user.getOwner(), value);

System.out.print("Computer rolled: " + value2 + "\n\n");

执行上述步骤后,您的代码将按预期工作。另外作为旁注,不要使用含义不明确的变量名,如value、value2等。


查看完整回答
反对 回复 2022-01-12
?
喵喵时光机

TA贡献1846条经验 获得超7个赞

每当您制作一个新骰子时,您的骰子value永远不会从零更改,从而导致该错误弹出,因为根据您的 Die 类,每当您调用 roll() 时它将查看的范围是 0 到 0。更改value为用户投入的价值并制造新的模具。


查看完整回答
反对 回复 2022-01-12
  • 2 回答
  • 0 关注
  • 151 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信