【问题标题】:Null Pointer Exception in array passed class数组传递类中的空指针异常
【发布时间】:2016-06-12 00:46:14
【问题描述】:

所以我有一个项目需要一个扩展 Number 的泛型类,并且还可以找到数组中的最大值和最小值、所有值的平均值以及数组的大小。这似乎很容易实现,但是在将其通用部分放置到位之前,我遇到了一个问题,无论我调用哪种方法,我都会在 x.length 处收到空指针异常的运行时错误,总是在同一个地方。

 import java.util.Comparator;

public class test
{
   public int x[];

   public test(int x[])
   {

   }

   public void setx(int newx[])
   {
   x = newx;
   }

   public int[] getx()
   {
   return x;
   }



public int findSmallest()
{
  int i = 0;
  int temp = x[i];

  while (i < x.length)
  {
      i++;
      if(x[i] < temp)
      {
      temp = x[i];      
      }
      else
      {

      }

   }

   return temp;

   }



public int findLargest()
{
  int i = 0;
  int temp = x[i];


  while (i < x.length)
  {
      i++;
      if(x[i] > temp)
      {
         temp = x[i];
      }
      else
      {

      }

   }

   return temp;

   }

public double findMean()
{
  int i = 0;
  double sum = 0.0;
  double avg = 0.0;

  while (i < x.length)
  {
      sum += x[i];
      i++;
  }

  avg = sum / x.length;
  return avg;
}

public int findTotal()
{

  int i = x.length;

  return i;

}

public static void main (String args[])
{

int[] ia = {1, 2, 3, 4, 5, 6};

test intTest = new test(ia);

System.out.println(intTest.findTotal());

}


}



Any help on how to fix this would be amazing.

【问题讨论】:

    标签: arrays class exception null


    【解决方案1】:

    你忘了在构造函数中使用 setx 方法。您将整数数组传递给构造函数,但实际上并未在类中初始化整数数组。您可以通过在构造函数中调用 setx 方法并将整数数组 x 传递给 setx 方法来完成此操作。 希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多