Cant figure out how to do this thing. I need to store and count number of "jumps" and direction of "jump" in array. Console has to display something like this:
: Jump 1, direction Left
: Jump 2, direction Right
In my code below, when I print array elements, int jump
always equals to 0;
I tried many variations, sometimes I got (for example):
jump();
jump();
jump();
jump();
And it prints: {0,0,0,4}
, instead of {1,2,3,4};
public class Jump {
int jump;
String direction;
Jump[] jumpArray = new Jump[100];
int storeJump;
String storeDirection;
public void jump() {
jump++;
if (jump > 50) {
System.out.println("need a rest");
return;
} else {
for (int i = 0; i < jumpArray.length; i++) {
jumpArray[i] = new Jump();
}
}
jumpArray[jump].storeJump = jump;
jumpArray[jump].storeDirection = direction;
}
public static void main(String[] args) {
Jump jumper = new Jump();
jumper.jump();
jumper.jump();
for (int i = 0; i < jumper.jump; i++) {
System.out.println(jumper.jumpArray[i].jump);
}
}
}
I think the code below will solve your problem, but I think You should improve your code.
int jump;
String direction;
Jump[] jumpArray = new Jump[100];
int storeJump;
String storeDirection;
public void jumping() {
jump++;
if (jump > 50) {
System.out.println("need a rest");
return;
} else {
jumpArray[jump] = new Jump();
}
jumpArray[jump].storeJump = jump;
jumpArray[jump].storeDirection = direction;
}
public static void main(String[] args) {
Jump jumper = new Jump();
jumper.jumping();
jumper.jumping();
Set<Jump> mySet = new HashSet<Jump>(Arrays.asList(jumper.jumpArray));
for (int i = 1; i < mySet.size(); i++) {
System.out.println(jumper.jumpArray[i].storeJump);
}
}