gpt4 book ai didi

java - 带有自己类的 NullPointerException

转载 作者:行者123 更新时间:2023-11-29 09:43:31 25 4
gpt4 key购买 nike

<分区>

我有点迷茫...我正在学习 Java 并且必须编写一个小型轮询命令行应用程序。

我们应该先用德语编写程序(为了我们所有人之间的一致性),所以我会尝试翻译它,以便您更容易阅读。我的问题是,它抛出异常(在编译时)如下:

Exception in thread "main" java.lang.NullPointerException

at communication.Poll.addQuestionItem(Poll.java:18)

at main.PollTool.main(PollTool.java:8)

我初始化我的数组“questionItems”是不是错了?我不应该那样做吗?这里出了什么问题?我忘了什么吗? :(

main.PollTool:

package main;
import communication.Poll;

public class PollTool {

public static void main(String[] args) {
Poll poll = new Poll ("Best Smartphone:",3);
poll.addQuestionItem("iPhone"); //<--line 8
poll.addQuestionItem("Android");
poll.addQuestionItem("Windows Phone");

poll.askQuestions("This poll determines the polularity of different Smartphones.");

}

}

交流。投票:

package communication;
import java.util.Scanner;
import calculations.QuestionItem;

public class Poll {
private String questionTitle;
private QuestionItem[] questionItems;
private int count;
private Scanner in = new Scanner(System.in);

public Poll(String s,int arraySize){
questionTitle = s;
questionItems = new QuestionItem[arraySize]; //<--problem here?
}

public void addQuestionItem(String s){
if(count<questionItems.length){
questionItems[count++].setItemText(s); // <--exception here
}
}

public void askQuestions(String topic){
System.out.println(topic);

System.out.println(questionTitle);
for(int i=0; i<questionItems.length; i++){
System.out.println("- - - "+ questionItems[i].getItemText() +" - - -");
System.out.print("Your numerical answer: ");
questionItems[i].vote(in.nextInt());
}
}

void evaluation(){
//not ready :)
}
}

计算.问题项:

package calculation;

public class QuestionItem {
int count;
int overall;
String text;

public void vote (int pointValue){
overall += pointValue;
count++;
}
public double getDurchschnitt(){
return (double) overall/count;
}
public void setItemText(String s){
text = s;
}
public String getItemText(){
return text;
}
}

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com