简体   繁体   中英

using variables to create random integers in java

Im creating a simple rpg game where you fight monsters. how your attack is generated is by generating a random number with the max set as your attack stat. the attack stat is declared at 0 at the begining of the class but later is set to one of 3 numbers (10,15,or20) later on depending on what class the player chooses. then i use this line to generate the players attack:

charDamage = rand.nextInt(charAttackTotal) + 10;

but when i run it it gives me an error saying n (charAttackTotal) must be positive.

this is how i get charAttackTotal:

static int charAttackBase = 0;   this is what is set to 10,15, or20

static int charAttackMod = 0;    this is set by what weapons the player has

static int charAttackTotal = charAttackBase + charAttackMod - 10;

but when i put this in an empty class it works just fine. Is this an error with having these variables declared outside the of the function (method) and then used inside the method or what? I have put all of the code on pastebin if you want to look at it heres a link:

http://pastebin.com/RBMScyss the error is on line 124 if your looking at pastebin, all of the variables are declared at the beginning though

Simply declaring

    static int charAttackTotal = charAttackBase + charAttackMod;

will not cause charAttackTotal to automatically update whenever you change charAttackBase or charAttackMod . You will need to explicitly update charAttackTotal whenever you make changes to the other variables.

Another way would be to calculate charAttackTotal whenever you need it, perhaps using a function.

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