我的随机数生成器不工作java [英] My random number generator is not working java

查看:119
本文介绍了我的随机数生成器不工作java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的随机数生成器不起作用,我不明白。我是android编程的新手,我无法弄清楚这个代码的和平。我已经尝试了几种方法,但它无法正常工作。请帮帮我,我是新的请不要惹火我。



例子:实际代码制作



第一套树木产生

1011010110



同一游戏中产生的第二组树木

100001111110011 < br $> b $ b

My random number generator is not working and I don't understand it. I am new to android programming and I can not figure out this peace of code. I have tried it several ways and it does not work properly. Please help me out, I am new please do not flame me.

Examples: of actual code production

First Set of trees spawned
1011010110

Second set of trees spawned within same game
100001111110011

import java.util.Random;
import android.util.Log;

public class Tree {
public Tree(int addition) {

   spawn = (int)(Math.random() * 2);
}



我也试过了。




I have also have tried.

private Random random = new Random();
public Tree(int addition) {

    int randomNum = random.nextInt(2);
    spawn = randomNum;
}



感谢您查看此内容。



Steve


Thanks for looking this over.

Steve

推荐答案

请参阅我对该问题的评论。我完全不知道到底出了什么问题,但我可以猜到。



如果你的例子,你可能期望{1,2}中的随机数字是你想要的。但是 random.nextInt(2)会在{0,1}中给出随机数,因为它产生的值介于0(包含)和你的参数2(独占)。请查看: http://docs.oracle.com/javase/6/ docs / api / java / util / Random.html [ ^ ]。



如果你想获得{1,2}中的值,只需将1添加到你的随机值。它将保持统一的统计分布。



您是否担心?



这个答案基于问题的第一个版本。



-SA
Please see my comment to the question. I don't know what is wrong, exactly, but I can guess.

Probably, you expect random numbers in {1, 2}, if your "example" is what you want. But random.nextInt(2) will give you random numbers in {0, 1}, because it produces the values in the range between 0 (inclusive) and your parameter 2 (exclusive). Check it out: http://docs.oracle.com/javase/6/docs/api/java/util/Random.html[^].

If you want to get values in {1, 2}, just add 1 to your random value. It will preserve the uniform statistical distribution.

Is that you were concerned with?

This answer was based on the first version of the question.

—SA


我的解决方案'



My solution'
in the update() method
if(setSpawn==1){
       int random = (int)(Math.random() *2);
       spawn=random;
       setSpawn=0;
    }


i suggest using the code below
private Random random = new Random();
   public Tree(int addition) {

       int randomNum = (int)(Math.random()*2);
       spawn = randomNum;
   }


这篇关于我的随机数生成器不工作java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆