簡體   English   中英

Java。 數組,保存以前的值

[英]Java. Array, save previous values

無法弄清楚該怎么做。 我需要存儲並計算數組中“跳轉”的數量和“跳轉”的方向。 控制台必須顯示以下內容:

:跳1,向左方向

:跳2,向右方向

在下面的代碼中,當我打印數組元素時, 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);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM