简体   繁体   English

如何在 Java 中生成多个随机变量?

[英]How do I generate multiple random variables in Java?

I am making a game where the user gets to pick the number of die for each roll.我正在制作一个游戏,用户可以在其中选择每卷的骰子数。 Right now my code is processing the users input correctly, but it only randomly generates the last number, the other numbers are 0. (For example if the user input 4 the roll would appear: [0,0,0,3] Does anyone know how to get all the numbers to generate random numbers? Here is my main:现在我的代码正在正确处理用户输入,但它只随机生成最后一个数字,其他数字为 0。(例如,如果用户输入 4,则会出现:[0,0,0,3] 有人知道如何让所有数字生成随机数吗?这是我的主要内容:

public class game
{
    public static void main(String[] args) 
  {
    int play = 1, sum = 0;
    int[] wins = new int[15];
    
    while ((play == 1) && (sum < 15)) 
    {
      sum = 0;;
      
      int roll = 0;
      Config die= new Config();
      //starts configuration
 
     
    die.hand();
    
      System.out.println("\nHere is your roll:\n");
      die.get();
    }
}

Here is my configure class:这是我的配置 class:

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

class Config
{
    public static int Dice;
    int i;
    public void hand()
    {
        System.out.println("\nLet's Configure the Game...\n");
    
        String file = "Config.txt";
        Scanner scan = new Scanner(System.in);

        //configures number of dice in hand
        System.out.println("Enter the number of dice you would like in your hand (1-5): ");
        int hand_count = scan.nextInt();
        int[] Dice = new int[hand_count];
        System.out.println("Here is your roll: \n");
        Random random= new Random();
        
       for (i = 0; i<hand_count - 1; i++);
        { 
            Dice[i] = random.nextInt(6) + 1; 
            System.out.println(Arrays.toString(Dice)); 
        }
        

        System.out.println("\nNow lets play the game...\n"); 
    
//s.close();
    }
    public int get()
    {
        return Dice;
    }
}
for (i = 0; i<hand_count - 1; i++);
        { 
            Dice[i] = random.nextInt(6) + 1; 
            System.out.println(Arrays.toString(Dice)); 
        }

You have a semi-colon at the end of the first line of this for loop, resulting in your loop having no contents.您在此 for 循环的第一行末尾有一个分号,导致您的循环没有内容。 Get rid of the semi-colon, and move your opening curly brace onto the same line as the for loop, ie去掉分号,将你的左大括号移动到与 for 循环相同的行上,即

for (i = 0; i<hand_count - 1; i++) {
  // do cool stuff
}

The answer by sunrise is good.日出前的答案是好的。 But I suggest using ThreadLocalRandom instead of java.util.Random .但我建议使用ThreadLocalRandom而不是java.util.Random Plus, your code has other issues to resolve.另外,您的代码还有其他问题需要解决。

ThreadLocalRandom

Using the ThreadLocalRandom class is thread-safe in case you ever use background threads.如果您曾经使用后台线程,使用ThreadLocalRandom class 是线程安全的。 And a single random-number generator per thread is established, available automatically for re-use, so less overhead for repeated use.并且每个线程都建立了一个随机数生成器,可以自动重复使用,从而减少重复使用的开销。

Like java.util.Random , ThreadLocalRandom offers some nifty methods for generating a series of numbers as a stream for use in modern Java.java.util.Random一样, ThreadLocalRandom提供了一些漂亮的方法来生成一系列数字作为 stream 用于现代 Java。 We can shorten the code to a single-line.我们可以将代码缩短为单行。

int countDice = 3;

// Bounds of random number are inclusive, exclusive. So (1,7) for six-sided dice.
int[] results = ThreadLocalRandom.current().ints( countDice , 1 , 7 ).toArray(); 

System.out.println( "results = " + Arrays.toString( results ) );

When run:运行时:

results = [4, 6, 4]

Other issues其他问题

Variable names should start in lowercase.变量名应以小写字母开头。 So public static int Dice;所以public static int Dice; should be public static int dice;应该是public static int dice; . .

Class names start in uppercase, by convention.按照惯例,Class 名称以大写开头。 So public class game should be public class Game .所以public class game应该是public class Game

Your class design is disorganized.您的 class 设计杂乱无章。 A key goal of object-oriented programming (OOP) is to more clearly model the entities being represented within your app.面向对象编程 (OOP) 的一个关键目标是更清楚地 model 在您的应用程序中表示的实体。 So I suggest you create a Die class to represent each die.所以我建议你创建一个Die class 来代表每个 die。 That class should have a roll method that generates a new value.那 class 应该有一个生成新值的roll方法。

In another class, instantiate some of these Die objects.在另一个 class 中,实例化其中一些Die对象。 Collect those instances in a collection named dice .在名为dice的集合中收集这些实例。 Then for each round of your game, call roll on each die.然后在你的每一轮游戏中,对每个骰子进行roll骰。

I was tempted to write more code for you, but this is obviously homework I'll go no further.我很想为你写更多的代码,但这显然是功课,我不会再写 go 了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM