简体   繁体   中英

Java: How to get length of array in different method?

A question in my Java textbook:


Complete this class:

public class MyMatrix
{
    public MyMatrix(int[][] elements)
    {
        // create new matrix with elements as the content
    }
    public int getRows()
    {
        // get the number of rows of the matrix
    }
}

Don't write any code outside the method bodies.


This is what I'm trying to do:

public class MyMatrix
{
    public MyMatrix(int[][] elements)
    {
        int[][] matrix = elements;
    }
    public int getRows()
    {
        return matrix.length;
    }
}

This obviously doesn't work since matrix is local to the constructor.

I don't see how I can make matrix available to other methods without working outside the method bodies. Could someone show me how to do this?

The only possible solution to your problem is to tell the "getRows()" method to take the Matrix as an argument.

This way, you are not creating code outside of the methods, rather using what you are given.


 public class MyMatrix { public MyMatrix(int[][] elements) { int[][] matrix = elements; int length = getRows(matrix); } public int getRows(int[][] matrix) { return matrix.length; } } 


Hope this answers your question.

Let me know what the outcome is :)

Good luck!

If the text book question is as you stated, then it is a trick question.

Clearly, if getRows must return the length of the array passed to the constructor, then there must be some information transfer from constructor to the method. That means there must be a variable that the constructor directly or indirectly writes and that the method directly or indirectly reads.

The best I can come up with is this:

public class Base {
    int[][] matrix;
    Base(int[][] elements) { matrix = elements; }
    int getRows() { return matrix.length; }
}

public class MyMatrix extends Base { 
    // No code added here
    public MyMatrix(int[][] elements) { super(elements); }
    public int getRows() { return super.getRows(); }
}

Or ... you could write it like this:

public class MyMatrix  { 
    // No "code" added outside of the method bodies.  This
    // is a declaration ... not "code".
    private int[][] array;
    public MyMatrix(int[][] elements) { array = elements; }
    public int getRows() { return elements.length; }
}

But these are both "trick" answers ... in that they are relying on sophistry over what "[d]on't write any code outside the method bodies" actually means. In fact, I don't think there is a solution that is not a trick answer in some sense.

Frankly, I doubt the wisdom including trick questions like this in a text book. The student won't learn how to program from trying (and failing) to solve trick questions!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM