【问题标题】:How to return an instance of an object from a method in java如何从java中的方法返回对象的实例
【发布时间】:2016-09-02 22:57:17
【问题描述】:

我不确定如何从具有值的方法返回对象的实例。有没有办法将 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 创建一个带有参数的构造函数,但我很不情愿,因为说明没有说要这样做。有没有其他方法可以做到这一点?谢谢

【问题讨论】:

  • 是的,你可以添加一个参数化的构造函数并创建一个Location。我不认为这是不正确的。不过你应该和你的讲师确认:)
  • @TheLostMind 是的,我是这么认为的,谢谢

标签: java oop object types return


【解决方案1】:

您的错误是,您将static 字段用于Object

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

每次调用

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

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

【讨论】:

  • 哦,是的,这是真的,谢谢!我实际上是想弄清楚是否有办法将“行”和“列”的值放在返回的“位置”实例中。但我才意识到我的愚蠢错误。我忘记了,如果我在 main 方法中创建一个对象,我可以将该方法称为“object.locateLargest”并使用“object.variable”来访问这些值。
猜你喜欢
  • 1970-01-01
  • 2012-08-17
  • 2012-04-10
  • 2010-10-02
  • 1970-01-01
  • 2021-01-18
  • 1970-01-01
  • 2020-02-11
  • 2021-05-15
相关资源
最近更新 更多