1

So I have a method that looks like this:

public Maze(String[] textmaze, int startRow, int startCol, int finishRow, int finishCol){
    int numRows = textmaze.length;
    int numCols = textmaze[0].length;
    int [][] x = new int[numRows][numCols];
    }

So I want to use the variables x, numRows and numCols in other methods however numRows and numCols needs the String textmaze which must be passed in as a parameter and the main method where this method is called is in another class which I'm not allowed to modify. So how can I use those variables in other methods?

3
  • 1- That's not a method, it's a constructor; 2- In that case, have you thought of providing getters for them...? Commented Mar 3, 2015 at 0:39
  • I've never used constructors like this in java and I also don't know what getters are. Commented Mar 3, 2015 at 0:41
  • A getter is an accessor method, it's simply a method that allows you to "get" a value from an object. While you may never have written one, I'm sure you've encountered them in one form or another Commented Mar 3, 2015 at 0:45

1 Answer 1

2

Since Maze is a constructor, and you want to use the variables in other parts of the class, you should make the variables instance fields instead, for example...

private int numRows;
private int numCols;
private int [][] x;

public Maze(String[] textmaze, int startRow, int startCol, int finishRow, int finishCol){
    numRows = textmaze.length;
    numCols = textmaze[0].length;
    x = new int[numRows][numCols];
}

This will allow you to access the variables from within THIS (Maze) classes context.

Depending on what you want to do, you could also provide accessors for the fields to allow child classes access to them (using protected to prevent other classes from outside the package from accessing them or public if you want other classes to access them)...

public int getNumRows() {
    return numRows;
}

Take a look at Understanding Class Members and Controlling Access to Members of a Class for more details

Sign up to request clarification or add additional context in comments.

2 Comments

I now have another problem. So for some reason when I compile it, I keep getting an error that says it cannot find the symbol on the line numCols = textmaze[0].length; and the arrow is pointing at the dot in textmaze[0].length. Do you know what's wrong?
textmaze is one dimensional array, either the parameter is wrong or you're trying to do something which is not achievable...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.