使用一个类来随机掷骰子

我正在编写一个骰子游戏程序,它为用户和计算机创建一个骰子,然后询问用户名、骰子的面数以及用户想在计算机上玩多少次迭代。然后让程序在每次掷骰后检查哪个掷骰更高,并在迭代结束时写回每个用户和计算机的总获胜次数以及获胜者是谁。我遇到的问题是我需要创建一个roll()类来随机化骰子并将其设置为用户滚动和计算机滚动的值,我收到此错误...


Exception in thread "main" java.lang.IllegalArgumentException: bound must be positive

at 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");

                }


}


}


函数式编程
浏览 236回答 2
2回答

森栏

以下是您的代码的问题:您永远不会返回该roll(...)方法生成的随机值public int roll(int rand){&nbsp; &nbsp; rand = r.nextInt(value);&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; return value;}将其更改为public int roll(int rand) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; return r.nextInt(rand);&nbsp; &nbsp; &nbsp;}在 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等。

喵喵时光机

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

相关分类

Java