【发布时间】:2015-10-22 05:05:42
【问题描述】:
我遇到了“java.lang.NullPointerException”问题。 这段代码的目的是生成具有特定大小的数组的随机数(在这种情况下,10 个数字,如驱动程序中给出的,但没关系),计算平均值,找到最大值、最小值和特定的数字(如驱动程序中给出的,2 和 3,但没关系)。我想我可以通过一些研究来编写所有这些代码,但是在完成所有工作并编译之后,我尝试运行代码,令我惊讶的是,我发现了 java.lang.NullPointerException。我不知道它是什么,但通过一些研究我学到了(我认为)我知道问题出在哪里。我想使用“for循环”访问一个数组,但我不能,因为数组的值为空。我不知道为什么,也不知道这段代码中的所有错误,因为我仍在尝试运行它。我只能编译,但正如我所说,我在运行时遇到了 NPE 问题。但是,对我来说,以我编写的方式接收参数和“for循环”的构造函数在逻辑上是可以接受的。 所以,当我运行时,消息正是这样的:
java.lang.NullPointerException 在 Driver.main(Driver.java:16) 处的 ArrayLab.initialize(ArrayLab.java:19)
我的问题是: 我的代码有什么问题?为什么我的数组为空并且没有在驱动程序中分配的值?如何为这个数组赋值?我的构造函数有什么问题吗?那么“for循环”呢?我能做些什么来修复它?
public class ArrayLab
{
private int[] ArrayNum;
public ArrayLab(int Num)
{
int[] ArrayNum = new int[Num];
}
public void initialize()
{
for (int ANUM = 0; ANUM <= ArrayNum.length; ANUM++)
{
ArrayNum[ANUM] = (int) Math.round((Math.random() * 10));
}
}
public void print()
{
System.out.println(ArrayNum);
}
public void printStats()
{
double Sum = 0;
int Max = 0;
int Min = 0;
for (int ANUM = 0; ANUM < ArrayNum.length; ANUM++)
{
Sum = Sum + ArrayNum[ANUM];
if (ArrayNum[ANUM] > ArrayNum[Max])
{
Max = ANUM;
}
if (ArrayNum[ANUM] < ArrayNum[Min])
{
Min = ANUM;
}
}
double Average = Sum/ArrayNum.length;
System.out.println("Average Value: " + Average);
System.out.println("Maximum Value: " + Max);
System.out.println("Minimum Value: " + Min);
}
public void search(int GivenNumber)
{
for (int ANUM = 0; ANUM < ArrayNum.length; ANUM++)
{
if(GivenNumber == ArrayNum[ANUM])
{
System.out.println(GivenNumber + " was found.");
}
else
{
System.out.println(GivenNumber + " was not found.");
}
}
}
}
和
public class Driver
{
public static void main(String[] args)
{
//create new instance of the ArrayLab class with parameter of 10
ArrayLab array = new ArrayLab(10);
//print out the array created by ArrayLab constructor
array.print();
//initialize the array with random values
array.initialize();
//print the randomized array
array.print();
//print stats for the array
array.printStats();
//search for 3
array.search(3);
//search for 2
array.search(2);
}
}
【问题讨论】:
-
调试您的代码并仔细查看错误消息中指定的行,您有一些为空的对象,但您尝试从该对象调用某些方法。因此你得到 NullPointerException。
-
在你的构造函数中,你已经重新声明了你的数组。所以你的实际数组没有被分配任何内存
-
我怀疑这是家庭作业,你们两个在同一个班。 stackoverflow.com/questions/33272636
-
是的,这是家庭作业。但我没有要求答案,因为我已经完成了大部分作业。反正我的问题已经解决了。谢谢大家的帮助。
标签: java arrays nullpointerexception