Restarting at the beginning of an array
Hi! I'm supposed to create a simple game that gains you points as the dice rolls and moves through the array. Basically, you enter an array. The dice is rolled, you move x amount of steps through the array. If you land on a 0, you lose. I'm having trouble figuring out how to restart at the beginning of the array once it moves through.
Here's what I have:
Code Java:
class A3Q2
{
public static void main (String[] args)
{
int [] a;
int dice;
char x = 'y';
int position = 0;
int points = 0;
System.out.println("Please enter an array.");
a = ITI1120.readIntLine( );
while (x == 'y')
{
dice = (int)(Math.random() * 5 + 1);
System.out.println("The number of steps taken was " + dice + ".");
position = position + dice;
while (position > a.length)
{
position = position - a.length;
}
if (a[position] != 0)
{
points = points + a[position];
System.out.println("You move in position " + position + " and you gain " + a[position] + " point(s). Total points: " + points);
System.out.println("Do you want to move again? (y/n)");
x = ITI1120.readChar();
}
else
{
System.out.println("You move in position " + position + " and you gain 0 points.");
System.out.println("Sorry, you lost.");
x = 'n';
}
}
}
}
My attempt at this is the second loop in the code, which I thought would work, but it doesn't... help please!
Re: Restarting at the beginning of an array
Hi bonbon242,
I don't know if I understand your problem, but I think that if position is 4 and a.length()=3, you want return at the first element of your array.
For me, if you use mod function, you do it...
Try
while (position >=a.length){
position = (position % a.length);
}
in the place of your while loop.
Tell me something!
Bye!
Re: Restarting at the beginning of an array
Oh! Thanks so much that's exactly what I was looking for :)