从对象调用数组?

时间:2015-11-15 17:06:37

标签: java arrays object

在我的类SummerStats中我需要创建另一个方法来定位在我的方法setSalaries中创建的数组的最大元素。如何调用数组,“薪水”到同一个类中的另一个方法?

class SummerStats
 {
   public SummerStats()
   {

   }
   public int[][] setSalaries(int people, int years)
   { 
      int[][] salaries = new int[people][years];

   //rows respresent people and columns represent years
      for (people = 0; people < salaries.length; people++)
      {
         for (years = 0; years < salaries[people].length; years++)
         {
            salaries[people][years] = (int)(1000 + Math.random()*1000);
         }
      }

      return salaries;
   }

另外,我的测试类是

import java.util.*;
public class testSummerStats
{
   public static void main (String[] args)
   {
   Scanner input = new Scanner(System.in);
   SummerStats one = new SummerStats();
   System.out.println("Enter people, then years: ");
   int x = input.nextInt();
   int y = input.nextInt();
   one.setSalaries(x, y);
   }
 }

4 个答案:

答案 0 :(得分:1)

setSalaries不应该返回数组。将数组分配给SummerStats字段。然后向SummerStats添加另一个方法以定位最大元素。

答案 1 :(得分:0)

将2D数组声明为成员变量。这样,该类的所有方法都可以访问它:

class SummerStats
 {
   private int[][] salaries;

   public SummerStats()
   {

   }

   public void setSalaries(int people, int years)
   { 
      salaries = new int[people][years]; // initialize the array

   //rows respresent people and columns represent years
      for (people = 0; people < salaries.length; people++)
      {
         for (years = 0; years < salaries[people].length; years++)
         {
            salaries[people][years] = (int)(1000 + Math.random()*1000);
         }
      }

   }
    public void locateMax() {
        // Your code goes here. (You can access the salaries array)
    }
}

然后创建一个新方法(locateMax,即),计算2D数组的最大数量。

答案 2 :(得分:0)

您可以将数组分配给字段。并在外面访问它。或者您可以传递第二个选项将此数组传递给新方法,然后您可以执行操作以查找最大元素。

答案 3 :(得分:0)

您当前的计划:

class SummerStats
 {
   public SummerStats()
   {

   }
   public int[][] setSalaries(int people, int years)
   **{** 
      int[][] salaries = new int[people][years];
      ....
      return salaries;
   **}**
}

<强>解决方案:

class SummerStats
 **{**
   private int[][] salaries;

   public SummerStats()
   {

   }
   public int[][] setSalaries(int people, int years)
   { 
      salaries = new int[people][years];
      ....
      return salaries;
   }
**}**

在当前程序中,变量salaries被声明为方法setSalaries的局部变量,因此其范围仅限于方法的范围。在解决方案程序中,变量salaries被声明为类SummerStats的成员变量/字段,因此其范围仅限于类的所有成员方法/变量声明的范围。