2016-05-08 400 views
0

我不知道如何從具有值的方法返回對象的實例。有什麼辦法將int類型轉換爲我的對象類型嗎? 下面是一些說明我有:如何從java中的方法返回對象的實例

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

我想我應該創建地點接受參數構造函數,但我不願意,因爲該指示並未說明如此。有沒有其他方法可以做到這一點?由於

+0

是的,你可以添加一個參數化的構造函數並創建一個'Location'。我不認爲這是不正確的。你應該與你的講師確認:) – TheLostMind

+0

@TheLostMind是我認爲是的,謝謝 –

回答

1

你的錯誤是,你正在使用static領域爲Object

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

每次調用

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

你認爲你正在創建一個新的Location對象不同maxValuerowcolumn,但由於這些字段是static,所以您只是重寫類變量。
只需刪除static修飾符。

+0

哦,是的,這是真的謝謝!實際上我試圖找出是否有辦法將「row」和「column」的值放入返回的「Location」實例中。但我只是意識到了我愚蠢的錯誤。我忘了,如果我在主方法中創建一個對象,我可以調用方法爲「object.locateLargest」,只需使用「object.variable」來訪問值。 –

相關問題