java - 如何从java中的方法返回对象的实例

标签 java oop object types return

我不确定如何从带有值的方法返回对象的实例。有什么方法可以将 int 类型转换为我的对象类型吗? 这是我的一些说明:

/* 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) */

这是我的代码:

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;
    }
}

我想我应该为带有参数的 Location 创建一个构造函数,但我不愿意,因为说明没有说这样做。还有其他方法可以做到这一点吗?谢谢

最佳答案

您的错误是,您正在为对象使用static字段:

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

每次打电话

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

您认为您正在创建一个具有不同 maxValuerowcolumn 的新 Location 对象,但因为这些字段是静态,您只是覆盖类变量。
只需删除 static 修饰符即可。

关于java - 如何从java中的方法返回对象的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37096594/

相关文章:

java - 尽管参数不同,方法还是递归调用?

javascript - oop 行为类似于构造函数参数类型的类

java - 单击按钮时如何调用servlet

java - 回文程序,无法终止循环,欧拉计划 #4

java - 需要澄清继承和异常

javascript - 使用对象的完整路径访问对象的属性值

javascript - 如何使用 jQuery 从对象获取数据?

Python:我应该将数据放在列表中还是对象属性中?

java - Java中的噪音和静音清除

c# - 如何通过实现适配器模式来隔离胖接口(interface)?