Nathaniel Brown
Nathaniel Brown

Reputation: 61

How to return an instance of an object from a method in java

I'm not sure how to return an instance of an object from a method with values. Is there some way to convert an int type into my object type? Here is some instructions I have:

/* Design a class named Location for locating a maximal value and its location in a
two-dimensional array. The class contains:

-Public double type data field maxValue that stores the maximal value in a two-dimensional
 array
-Public int type data fields row and column that store the maxValue indices in a
 two-dimensional array

Write a the following method that returns the location of the largest element in a two
dimensional array:

    public static Location locateLargest(double[][] a)

The return value is an instance of Location. Write a test program that prompts the user to
enter a two-dimensional array and displays the location of the largest element in the
array. Here is a sample run:

Enter the number of rows and columns in the array: 3 4
Enter the array:
23.5 35 2 10
4.5 3 45 3.5
35 44 5.5 9.6
The location of the largest element is 45 at (1, 2) */

And here is my code:

class Location {

    public static double maxValue;
    public static int row;
    public static int column;

    public static Location locateLargest(double[][] a) {

        maxValue = a[0][0];
        row = 0;
        column = 0;

        Location result = new Location();

        for(int i = 0; i < a.length; i++) {
            for(int j = 0; j < a[i].length; j++) {

                if(a[i][j] > maxValue) {

                    maxValue = a[i][j];
                    row =  i;
                    column = j;

                    if((i == a.length-1) && (j == a[i].length-1))
                        //Place indices of maxValue in result variable
                }

                else
                    continue;

            }
        }

        return result;
    }
}

I'm thinking I should just create a constructor for Location that takes arguments, but I'm reluctant because the instructions didn't say to do so. Is there any other way to do this? Thanks

Upvotes: 0

Views: 3812

Answers (1)

Alireza Mohamadi
Alireza Mohamadi

Reputation: 521

Your mistake is, you are using static fields for an Object:

public static double maxValue;
public static int row;
public static int column;

Each time you call

public static Location locateLargest(double[][] a)

You think that you are creating a new Location object with different maxValue, row and column but because these fields are static you are just overriding class variables.
Just remove static modifier.

Upvotes: 2

Related Questions