繁体   English   中英

生成由实例变量传递的随机数的Java方法

[英]Java method that generates random numbers passed by instance variables

我正在用 Java 制作一个基于文本的游戏,我正在使用一个类和实例变量,我正在尝试创建一个方法,该方法根据实例变量max_attack的数字生成一个随机数。

public class badPlayer 
{
    String description;
    int health;
    int award;
    int max_attack;

    public badPlayer(String description, int health, int award, int attack){            
        this.description=description;
        this.health = health;
        this.award = award;
        this.max_attack = attack;
    }

   Random rnd = new Random();

    public int maxAttack(){ 
        int rand_int1 = rnd.nextInt(max_attack);
        return rand_int1;   
    }   
}

public class troll extends badPlayer
{
    troll(int attack){
        super("troll", 100, 50, 100);
    } 
}

输出

巨魔1005089

我想要在 1 到 100 之间创建随机数的方法。

Random r = new Random();
int low = 1;
int high = 100;
int result = r.nextInt(high-low) + low;

Java 在两个给定值之间生成随机数

我正在使用Java开发基于文本的游戏,正在使用类和实例变量,并且试图创建一种基于实例变量max_attack的数量生成随机数的方法。

public class badPlayer 
{
    String description;
    int health;
    int award;
    int max_attack;

    public badPlayer(String description, int health, int award, int attack){            
        this.description=description;
        this.health = health;
        this.award = award;
        this.max_attack = attack;
    }

   Random rnd = new Random();

    public int maxAttack(){ 
        int rand_int1 = rnd.nextInt(max_attack);
        return rand_int1;   
    }   
}

public class troll extends badPlayer
{
    troll(int attack){
        super("troll", 100, 50, 100);
    } 
}

输出

巨魔

我想要创建1到100之间的随机数的方法。

int result = 1 + random.nextInt(100);

结果 - 从 1 到 100 的随机数https://docs.oracle.com/javase/8/docs/api/java/util/Random.html#nextInt--

暂无
暂无

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

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