Here is my first class called World
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();
}
}
}
Here is my second class called Driver
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();
}
}
Why don't I need to call displayWorld specifically on the myWorld instance of the World class?
What if I created multiple World instances? This can't be right.
**edit for more detail
I want to call one of the class methods (i.e. moveUp or moveDown) on the instance of the World class myWorld object. However, I can't pass my reference to that object (myWorld) into those methods. I want to be able to call one of those methods, which changes the postion of 'P' in the 2 dimensional array and print it out using the methods that I have defined including the displayWorld method