如何将一种方法与另一种方法一起使用

时间:2019-10-12 05:36:55

标签: java

老实说,我不知道该如何处理,这意味着当用户在类Player的move方法中输入距离时,玩家的位置会相应地移动。我还希望Jar的位置根据玩家移动的距离移动相同的量。


public class Player
{
    // instance variables - replace the example below with your own
    private String name;
    private int position;
    private Jar jar;

    public Player()
    {
        position = 0;
        jar = new Jar();

        System.out.print("Enter player's name: ");
        this.name = Global.keyboard.nextLine();

    }

    public int move(int distance)
    {
        position = position + distance;
    }
}


public class Jar
{
    private int position;
    private Stone stone;


    public Jar()
    {
        position = 0;
        stone = null;
    }

    public Jar(int initPos, Stone stone)
    {
        position = initPos;
        this.stone = stone;
    }

     public void move()
    {
        Player move = new Player();
    }
}

2 个答案:

答案 0 :(得分:3)

您可以在Jar中修改Player的位置。另外,您可能不想每次更改职位都创建一个新的Player

public class Player {

    ...

    public int move(int distance) {
        position = position + distance;
        jar.move(distance);
    }
}


public class Jar {
    private int position;
    private Stone stone;

    public Jar() {
        position = 0;
        stone = null;
    }

    public Jar(int initPos, Stone stone) {
        position = initPos;
        this.stone = stone;
    }

     public void move(int distance) {
        position += distance;
    }
}

答案 1 :(得分:1)

我将方法更改为void,因为没有理由返回值  当move方法获取距离值时。它将同时更改Player类实例的位置。它将调用Jar实例move方法。 调用Jar类实例的move方法时,jar的位置也会更改。查看Jar Move方法

public class Player
{
    // instance variables - replace the example below with your own
    private String name;
    private int position;
    private Jar jar;

    public Player()
    {
        position = 0;
        jar = new Jar();

        System.out.print("Enter player's name: ");
        this.name = Global.keyboard.nextLine();

    }

    public void move(int distance)
    {
        position = position + distance;
        jar.move(distance); 
    }
}


public class Jar
{
    private int position;
    private Stone stone;


    public Jar()
    {
        position = 0;
        stone = null;
    }

    public Jar(int initPos, Stone stone)
    {
        position = initPos;
        this.stone = stone;
    }

     public void move( int distance)
    {
       position = position+distance;
    }
}
```