简体   繁体   English

使用变量在java中创建随机整数

[英]using variables to create random integers in java

Im creating a simple rpg game where you fight monsters. 我创建了一个简单的RPG游戏,你可以对抗怪物。 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. 攻击属性在课程开始时声明为0,但稍后将根据玩家选择的等级设置为3个数字(10,15或者20)中的一个。 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. 但当我运行它时,它给我一个错误,说n(charAttackTotal)必须是正面的。

this is how i get charAttackTotal: 这就是我如何得到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: 我把所有的代码都放在了pastebin上,如果你想看看它是一个链接:

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 http://pastebin.com/RBMScyss错误在第124行,如果你看看pastebin,所有变量都在开头声明了虽然

Simply declaring 简单地宣布

    static int charAttackTotal = charAttackBase + charAttackMod;

will not cause charAttackTotal to automatically update whenever you change charAttackBase or charAttackMod . 每次更改charAttackBasecharAttackMod时,都不会导致charAttackTotal自动更新。 You will need to explicitly update charAttackTotal whenever you make changes to the other variables. 每当您对其他变量进行更改时,您将需要显式更新charAttackTotal

Another way would be to calculate charAttackTotal whenever you need it, perhaps using a function. 另一种方法是在需要时计算charAttackTotal ,可能使用函数。

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

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