简体   繁体   中英

Java method that generates random numbers passed by instance variables

I am working on making a text based game in Java, I am using a class and instance variables and I am trying to create a method that generates a random number based on the number that the instance variable max_attack has.

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);
    } 
}

Output

troll1005089

I would like the method to create random numbers between 1 and 100.

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

Java Generate Random Number Between Two Given Values

I am working on making a text based game in Java, I am using a class and instance variables and I am trying to create a method that generates a random number based on the number that the instance variable max_attack has.

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);
    } 
}

Output

troll1005089

I would like the method to create random numbers between 1 and 100.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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