这是我的第一堂课,叫做世界

public class World {

    private static char[][] world2D;
    private int characterRow;
    private int characterColumn;


    public World(int width, int height){
        world2D = new char[width][height];
        characterColumn = 0;
        characterRow = 0;

        for(int i = 0; i < world2D.length; i++){
            for(int j = 0; j < world2D[i].length; j++){
                world2D[i][j] = '-';
            }
        }

        world2D[characterRow][characterColumn] = 'P';
    }

    public void moveUp(){
        world2D[characterRow][characterColumn] = '-';
        if (characterRow > 0){
            characterRow -= 1;
        }
        world2D[characterRow][characterColumn] = 'P';
    }

    public void moveDown(){
        world2D[characterRow][characterColumn] = '-';
        if (characterRow < world2D.length){
            characterRow += 1;
        }
        world2D[characterRow][characterColumn] = 'P';
    }

    public void moveRight(){
        world2D[characterRow][characterColumn] = '-';
        if (characterColumn < (world2D[characterRow].length - 1)){
            characterColumn += 1;
        }
        world2D[characterRow][characterColumn] = 'P';
    }

    public void moveLeft(){
        world2D[characterRow][characterColumn] = '-';
        if (characterColumn > 0){
            characterColumn -= 1;
        }
        world2D[characterRow][characterColumn] = 'P';
    }

    public static void displayWorld(){
        for(int i = 0; i < world2D.length; i++){
            for(int j = 0; j < world2D[i].length; j++){
                System.out.print(world2D[i][j]);
            }
            System.out.println();
        }
    }

}


这是我的第二节课,叫做驱动程序

import java.util.Scanner;

public class Driver {
    public static void main(String[]args){
        @SuppressWarnings("resource")
        Scanner input = new Scanner(System.in);
        System.out.print("How tall should the world be?: ");
        int height = input.nextInt();
        System.out.print("How wide should the world be?: ");
        int width = input.nextInt();

        World myWorld = new World(width,height);
        World.displayWorld();
    }

}


为什么我不需要在World类的myWorld实例上专门调用displayWorld?

如果我创建了多个世界实例怎么办?这是不对的。

**编辑以获取更多详细信息

我想在World类myWorld对象的实例上调用类方法之一(即moveUp或moveDown)。但是,我无法将对那个对象(myWorld)的引用传递给那些方法。我希望能够调用这些方法之一,该方法将更改二维数组中“ P”的位置并使用我定义的方法(包括displayWorld方法)将其打印出来

最佳答案

请参考链接以了解有关static类型的更多信息。
如果要显示不同实例的世界,请从static中删除​​public static void displayWorld()并调用myWorld.displayWorld()

10-08 21:48