This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
I am following the ebook Big Java Late Objects - and I have problem resolving on of the tasks. It is about inheritance. There is Question class and one sub ChoiceQuestion class that extends it.
But when I run the code in my testclass it calls the null exception and I don't know why.
Exception in thread "main" java.lang.NullPointerException
at ChoiceQuestion.addChoice(ChoiceQuestion.java:12)
at TestClass.main(TestClass.java:21)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Here are my classes:
public class Question {
private String text;
private String answer;
/**
* Constructs a queston with empty question and answer.
*/
public Question(){
text = "";
answer = "";
}
//=============Setter methods============
public void setText(String questionText){
text = questionText;
}
public void setAnswer(String correctResponse){
answer = correctResponse;
}
//==============Getter Methods=============
public boolean checkAnswer(String response){
return answer.equals(response);
}
public void display(){
System.out.println(text);
}
}
And here is my subclass:
class ChoiceQuestion extends Question {
private ArrayList<String> choices;
//=========Methods==============
public void addChoice(String choice,boolean correct){
choices.add(choice);
if(correct){
//convert choices.size() to string
String choiceString = "" + choices.size();
this.setAnswer(choiceString);
}
}
public void display(){
// Display the question text
super.display();
// Display the answer choices
for(int i=0;i<choices.size();i++){
int choiceNumber = i + 1;
System.out.println(choiceNumber + ": " + choices.get(i));
}
}
}
And my test Class:
import java.util.Scanner;
public class TestClass {
public static void presentQuestion(Question q){
q.display();
System.out.println("Your answer: ");
Scanner in = new Scanner(System.in);
String response = in.nextLine();
System.out.println(q.checkAnswer(response));
}
public static void main(String[] args) {
Question first = new Question();
first.setText("James Gosling");
first.setAnswer("James Gosling");
ChoiceQuestion second = new ChoiceQuestion();
second.setText("In which country was the inventor of Java born? ");
second.addChoice("Austria", false);
second.addChoice("Canada",true);
second.addChoice("Denmark",false);
second.addChoice("United States",false);
presentQuestion(first);
presentQuestion(second);
}
}
Object choices is never initialized.
In Java, objects must be initialized before you can use them. That's why an attempt to call choices.add(choice) yields such an exception.
It is often a good idea to initialize member objects in constructors.
In this case, it looks like you should write a constructor for ChoiceQuestion and initialize your choices ArrayList there.
class ChoiceQuestion extends Question {
private ArrayList<String> choices;
ChoiceQuestion(){
choices = new ArrayList<>();
}
//...
Write private ArrayList choices = new ArrayList();
In the class when you declared it.
You need to initialize your list before use:
private List<String> choices = new ArrayList<String>();
The choices member is never initialized, so the first time you try to access it, you fail with a NullPointerException. You could, for example, initialize it in the class definition:
class ChoiceQuestion extends Question {
private ArrayList<String> choices = new ArrayList<>();
// Rest of the class
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I have a problem with this part of the code. It seems that if I try to add something to a list of Client I get a NullPointerException. I really don't know why because if I debug this part of the code the variable of type Client has information. If someone can help me I would be grateful. Here is the part of the code where the exception appears:
public class Customers {
private ArrayList<Client> listaClienti;
public Customers()
{
}
public void addClient(Client c,int i)
{
listaClienti.add(i, c);
}
public void deleteClient(Client c)
{
listaClienti.remove(c);
}
public Client getClient(int id)
{
return listaClienti.get(id);
}
}
You are not instantiating your list:
private ArrayList<Client> listaClienti = new ArrayList<>();
You may also instantiate inside your class constructor if you wish:
public Customers() {
listaClienti = new ArrayList<>();
}
You got a NullPointerException because you didn't initialize your list
private List<Client> listaClienti = new ArrayList<>();
first you have to insatantiate your array
ArrayList<Client> listaClienti = new ArrayList<>();
or
public Customers()
{
listaClienti = new ArrayList<Client>();
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
Say I have the class:
package school;
public class SchClass {
private Student[] students;
private int numStudents = 0;
public SchClass() {
}
public void addStudent(Student s) {
this.students[this.numStudents] = s;
this.amountStudents++;
}
}
and I am trying to run this in another class:
import school.SchClass;
import school.Student;
import school.Tutor;
public class JavaTesting {
public static void main(String[] args) {
Student s = new Student();
Tutor t = new Tutor();
SchClass shc = new SchClass();
sch.setTutor(t);
sch.addStudent(s);
}
}
When I do this, it reports this NullPointerException:
Exception in thread "main" java.lang.NullPointerException
at school.SchClass.addStudent(SchClass.java:8)
at javatesting.JavaTesting.main(JavaTesting.java:10)
What is wrong? I'm sure I coded this perfect but it still reports an error.
member students is null
public class SchClass {
private Student[] students = new Student[ size ];
private int numStudents = 0;
public SchClass() {
}
public void addStudent(Student s) {
this.students[this.numStudents] = s;
this.amountStudents++;
}
}
and it will work only untils amountStudents < size, then execption will occur so better is
public class SchClass {
private List< Student > students = new ArrayList< Student >();
public SchClass() {
}
public void addStudent(Student s) {
this.students.add( s );
}
}
Read about the Collection framework. If you want dynamic "arrays" you may use List<T>
Arrays are not dynamic.
Also, you have numerous errors in your class. What is for example this.amountStudents++ supposed to do? Furthermore I am surprised that your code does not already fail at sch.setTutor(t);, since you do not have declared a variable called sch. Did you mean shc?
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
Here is the exact error message:
Exception in thread "main" java.lang.NullPointerException
at Application.main(Application.java:22)
I've tried to fix it with what I know... what am I doing wrong?
My code:
public class Application {
private String guitarMaker;
public void setMaker(String maker) {
guitarMaker = maker;
}
public String getMaker() {
return guitarMaker;
}
public static void main (String[] args) {
Application[] guitarists;
guitarists = new Application[1];
guitarists[0].setMaker("Example maker");
System.out.println("My guitar maker is " + guitarists[0].getMaker());
}
}
new Application[1] creates an array of one element, and all elements in that array (in this case, "all the elements" is "that only element") are null by default. That means that guitarist[0] is null, and calling setMaker on it will result in the NullPointerException.
You need to instantiate a guitarist and set assign it to guitarist[0]:
guitarist[0] = new Application();
public class Application {
private String guitarMaker;
public void setMaker(String maker) {
guitarMaker = maker;
}
public String getMaker() {
return guitarMaker;
}
public static void main (String[] args) {
Application[] guitarists;
guitarists = new Application[1];
guitarists[0] = new Application(); //need to create a new object
guitarists[0].setMaker("Example maker");
System.out.println("My guitar maker is " + guitarists[0].getMaker());
}
}
You were calling a method on a null object. The new Application[1] just creates an array after that you need to make new objects in each index of the array
you have to initialise array with size and call new Application() instead of new Application[1] something like:
Application[] guitarists = new Application[1];
guitarists[0] = new Application();
guitarists[0].setMaker("Example maker");
System.out.println("My guitar maker is " + guitarists[0].getMaker());
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
been struggling with this problem since a couple of hours. Including looking through the previous questions answered. (Im really new in Java, basicly started a couple of days ago)
it keeps giving me NullpointerExceptions between Register.läggTillhund(nyHund); in the first class and hundRegister.add(nyHund); in the second class.
I have no idea what might be causing them. Does anyone have Ideas?
The purpose of the code (when finished) is to add an object from the 3rd class, into a list in the secondclass using the firstclass as the "main program".
Thanks for the help!
Oskar
First Class (Main)
public class testning {
public static void main(String[] args) {
Hund nyHund = new Hund("Daisy", 13, "labrador", 22.3);
System.out.println(nyHund.toString());
System.out.println(nyHund);
Register.läggTillHund(nyHund);
}
}
Second Class:
import java.util.ArrayList;
public class Register {
private static ArrayList<Hund> hundRegister;
public static void läggTillHund(Hund nyHund){
hundRegister.add(nyHund);
System.out.println(nyHund);
}
public Register(){
hundRegister = new ArrayList<Hund>();
}
}
Third Class
public class Hund {
private String namn;
private int ålder;
private double vikt;
private String ras;
public Hund(String hundnamn, int hundålder, String hundras, double hundvikt) {
this.namn = hundnamn;
this.ålder = hundålder;
this.ras = hundras;
this.vikt = hundvikt;
}
public String getNamn() {
return namn;
}
public int getÅlder() {
return ålder;
}
public double getSvanslängd() {
if ("tax".equals(ras)){
return 3.7;
}else{
return ((vikt*ålder)/10);
}
}
public String toString() {
return namn + "\n" + ålder + "\n"+ras+"\n"+vikt+"\n"+getSvanslängd();
}
}
You're accessing static method. In this case constructor never working. Use private static ArrayList<Hund> hundRegister = new Arraylist<>() ;and delete the constructor. To see what's going on add System.out.println line to construct and you'll see it will never works
I am trying to create a class. Let's call it Questionnaire. In Questionnaire, I want to instantiate a number of classes called Question. The constructor for Questionnaire accepts a string array of words, and for each word, there should be a Question class to accept it as an argument for its constructor. In other words, for every string that is passed as an argument, I want to create a Question.
I need to be able to put Questionnaire within a bigger class and still call the methods of the Question classes. The size of the array passed to Questionnaire varies as well. I don't know how I can put multiple classes within another class when I don't know how many classes there will be, and how to reference them from an outer class. If the array was a fixed length I'd just create Questions as question1, question2, question3... but since this is not the case I am not sure anymore. I do know there is a maximum number of Question classes I want to create though.
edit: I'm using J2ME CDLC 1.1 MIDP 2.0 for this (it's part of a mobile phone app) so my solutions are constrained by what it offers.
You don't want to have a separate variable per question - use a List<Question> to have one variable which refers to a collection of questions:
public class Questionnaire
{
private final List<Question> questions;
public Questionnaire(String[] words)
{
questions = new ArrayList<Question>();
for (String word : words)
{
questions.add(new Question(word));
}
}
// Use questions here
}
EDIT: If you're in an environment without generics, you could use the non-generic form, like this:
private final List questions;
public Questionnaire(String[] words)
{
questions = new ArrayList();
for (String word : words)
{
questions.add(new Question(word));
}
}
or like this if you don't have List/ArrayList:
private final Vector questions;
public Questionnaire(String[] words)
{
questions = new Vector();
for (String word : words)
{
questions.add(new Question(word));
}
}
In either case you'll need to cast on every access. Alternatively, you could use an array:
private final Question[] questions;
public Questionnaire(String[] words)
{
questions = new Question[words.length];
for (int i = 0; i < words.length; i++)
{
questions[i] = new Question(word);
}
}
As J2ME API lacks the Collections API, your best bet is to grab a Vector.
Vector questions = new Vector();
for (int i = 0; i < words.length; i++) {
questions.addElement(new Question(words[i]));
}
You probably want to go with a Set of questions rather than List. Try :
private final Set<Question> questions;
This will prevent duplicate questions. Everything else will be the same as JonSkeet's answer.
Why don't you use a List on the questionaire and for each question you add you add one to the List, for example.
public class Questionnaire
{
public List<Question> myQuestions {get; private set;}
public Questionnaire(string[] questions)
{
myQuestions = new List<Questions>();
foreach(string q in questions)
{
myQuestions.Add(new Question {questionText = g});
}
}
}
public class Question
{
public string questionText {get; set;}
}
Then you will be able to check the questions from outside... this is what you want?
Hope this helps
EDIT: ohh is Java, but you got the idea right?
import java.util.*;
public class Questionnaire implements Iterable<Question> {
private final List<Question> questions;
public Questionnaire(String ...words) {
questions = new ArrayList<Question>(words.length);
for(String word : words) {
questions.add(new Question(word));
}
}
// allows you to use a Questionnaire object in a for-each loop
public Iterator<Question> iterator() { return questions.iterator(); }
#Override
public String toString() { return questions.toString(); }
}
You could add many more goodies to your class to make it more useful. An example of using the class above follows:
public class QuestionnaireTest {
public static void main(String[] words) {
Questionnaire questionnaire = new Questionnaire(words);
for(Question q : questionnaire) {
System.out.println("You asked: " + q);
}
}
}
You could also use it as follows:
public class QuestionnaireTest3 {
public static void main(String[] words) {
// because I declared the constructor to accept "String ...words", I can specify as many questions as I want using simple syntax
Questionnaire questionnaire = new Questionnaire("How deep the ocean?", "How high the moon?");
for(Question q : questionnaire) {
System.out.println("I asked: " + q);
}
}
}
Even though I did so in my first example above, you should really accept an array of String objects as questions. Here's a better design:
public class Questionnaire implements Iterable<Question> {
private List<Question> questions = new ArrayList<Question>();
public void add(Question q) {
if(q == null) throw new IllegalArgumentException("can't add null question!");
questions.add(q);
}
public Question get(int index) {
if(index < 0 || index >= questions.size()) throw new IndexOutOfBoundsException("invalid question index: " + index);
return questions.get(index);
}
// allows you to use a Questionnaire object in a for-each loop
public Iterator<Question> iterator() {
return Collections.unmodifiableList(questions).iterator();
}
#Override
public String toString() { return questions.toString(); }
}
public abstract class Question {
public String getText();
public String getAnswer();
public String getOptions();
// ...
}
public class YesNoQuestion extends Question {
private final String text;
private final String answer;
public YesNoQuestion(String text, boolean answer) {
if(!(text.startsWith("Is"))) throw new IllegalArgumentException("Must start with is: " + text);
this.text = text;
this.answer = answer ? "Yes" : "No"; // if answer == true, the "Yes",...
}
#Override
public String getText() { return text; }
public String getAnswer() { return answer; }
public String getOptions() { return "Yes or No ?"; }
}
And now you can use it as follows:
public class QuestionnaireTest4 {
public static void main(String[] words) {
Questionnaire test = new Questionnaire();
test.add(new YesNoQuestion("Is dogs animals?", false));
test.add(new YesNoQuestion("Is me has cheezburgers?", true));
for(Question q : questionnaire) {
System.out.println(q);
System.out.println(q.getOptions());
String input = null; // you need to code this part
if(q.getAnswer().equals(input))
System.out.println("CORRECT!");
else
System.out.println("YOU IS STUPID!!!!");
}
}
}