1

I have declared:

Discursiva[] questoesDiscursivas = new Discursiva[10];

Which is:

public class Discursiva extends Questao{
    private String criteriosCorrecao;
}

And Questao is:

public class Questao {
    private String pergunta;
    private double peso;
}

So I just did:

str = JOptionPane.showInputDialog("Pergunta da Questao:");
questoesObjetivas[i].setPergunta(str);

And got java.lang.NullPointerException.

I have read in oracle docs: Thrown when an application attempts to use null in a case where an object is required. These include:

Calling the instance method of a null object. 
Accessing or modifying the field of a null object. 
Taking the length of null as if it were an array. 
Accessing or modifying the slots of null as if it were an array. 
Throwing null as if it were a Throwable value.

And I dont get why I am receiving NullPointerException. Please dont bottomrate my question, Iam still learning Java, its like my first code in it and I would like your help, so please, how can I fix this?

4

7 回答 7

6

您的数组中充满了nulls。

您需要new Discursiva()在数组的每个插槽中放置一个,然后才能使用它。

于 2012-09-03T14:17:39.833 回答
3

在执行此操作之前,questoesObjetivas[i]请先执行此操作

 questoesObjetivas[i] = new Discursiva();

你会在这里找到一篇好文章。

如果声明对象数组,则数组仅包含对对象的引用。对象数组中的每个值都初始化为空。所以当你尝试访问它时,你会得到NullPointerException

因为数组covariant [if Sub is a subtype of Super, then the array type Sub[] is a subtype of Super[] **Effective Java**]本质上应该更喜欢ArrayList

ArrayList<Discursiva> questoesDiscursivas = new ArrayList<Discursiva>(10);
questoesDiscursivas.add(new Discursiva());

您可以在有效的 Java中阅读更多内容 Item 25: Prefer lists to arrays

于 2012-09-03T14:17:35.633 回答
2

您需要在数组中创建对象:

Discursiva[] questoesDiscursivas = new Discursiva[10];

for (int i=0;i<10;i++){
    questoesDiscursivas = new Discursiva();
}
于 2012-09-03T14:17:38.833 回答
1

您已声明 questoesObjetivas[i],但未对其进行初始化。

于 2012-09-03T14:20:30.533 回答
0

Upon creation, all of the elements of object arrays are initialized to null, so questoesObjetivas[i].setPergunta(str) will give a NullPointerException since the ith element of that array is indeed null. Try filling the array with instances of the Discursiva class.

于 2012-09-03T14:18:24.180 回答
0

猜测问题出在您给出的两行中:

questoesObjetivas[i]为空或questoesObjetivas为空

于 2012-09-03T14:18:45.413 回答
0

你需要实例化一个对象,这样你就可以把它放在你的数组中:

   questoesObjetivas[i] = new setPergunta(str);
于 2012-09-03T14:19:18.017 回答