Java。数组,保存以前的值

Java. Array, save previous values

不知道该怎么做。我需要在数组中存储和计算 "jumps" 的数量和 "jump" 的方向。 控制台必须显示如下内容:

: Jump 1, direction Left

: Jump 2, direction Right

在我下面的代码中,当我打印数组元素时,int jump 总是等于 0;

我尝试了很多变化,有时我得到(例如):

jump();

jump();

jump();

jump();

并打印: {0,0,0,4} ,而不是 {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);

    }

}

}

我认为将 jumpArray 移动到 main() 更有意义:

public class Jump {
    String direction;
    //int storeJump;   Not sure what this is for
    //String storeDirection;    Or this

    @Override
    public String toString() {
        return direction;
    }

    // Static function that creates an initializes a Jump object
    public static Jump jump(String direction) {
        Jump jump = new Jump();
        jump.direction = direction;
        return jump;
    }

    public static void main (String[] args)
    {
        Jump[] jumpArray = new Jump[100];
        int numJumps = 0;

        // A list of directions for testing
        String [] path = new String[]{"north", "south", "east", "west"};

        // Create a bunch of jumps
        for (String dir : path) {
            if (numJumps > 50) {
                System.out.println("need a rest");
                break;
            }
            // Create a new jump and add to the array
            jumpArray[numJumps++] = Jump.jump(dir);
        }

        // Print the jumps
        for (int i = 0; i < numJumps; i++) {
            System.out.println(i + " " + jumpArray[i]);
        }
    }
}

我认为下面的代码可以解决您的问题,但我认为您应该改进您的代码。

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);
    }
}