The problem is on line 3, I need to take away a number between 1-3 and save the value so more can be taken away.
Random randomhit = new Random();
int randomNumberhit = randomhit.Next(1, 4);
int life = life - randomNumberhit;
Console.WriteLine(life);
Any ideas? Am I doing it completely wrong?
You're declaring the variable life
and assigning it a value of life - randomhit
. How can you know the result of the calculation if life
doesn't yet have a value?
Try something like this:
int life = 100;
...
Random randomhit = new Random();
int randomNumberhit = randomhit.Next(1, 4);
life = life - randomNumberhit;
Console.WriteLine(life);
However, you may want to make life
class variable instead. Something like this would work:
public class MyGuy
{
public int Life { get; set; }
public MyGuy()
{
this.Life = 100; // starting life
}
public void Hit()
{
Random randomhit = new Random();
int randomNumberhit = randomhit.Next(1, 4);
this.Life -= randomNumberhit;
Console.WriteLine(this.Life);
}
}
life need to be initalized to something
int life = 100; //Or some other value
Random randomhit = new Random();
int randomNumberhit = randomhit.Next(1, 4);
life = life - randomNumberhit;
Console.WriteLine(life);
Also note that when life is reassigned ( life = life - randomNumberhit;
) the int is not needed.
You are doing life-randomNumberhit
, but at that point your variable life
does not exist yet. You should initialize your life
variable to whatever value you want:
Random randomhit = new Random();
int randomNumberhit = randomhit.Next(1, 4);
int life = 0; // for instance, 0
Console.WriteLine(life - randomNumberhit);
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.