Nullpointerexception and no compilation errors. Can't find cause [duplicate] - java

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

Related

How to store objects in ArrayList and print it? [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
for loop without braces in java
(6 answers)
Closed 4 years ago.
i am working in my project and it is about a clinic , my class is appointment , and i have to let the user to enter the day, time, section, doctor name, patient name. and store it an ArrayList
i wrote the code but when i run the project there is no output and i don't know why :(
package appointments;
import java.util.Scanner;
import java.util.ArrayList;
public class Appointment {
public static void main(String[] args) {
ArrayList<Object> appointments = new ArrayList<>();
Scanner input = new Scanner (System.in);
System.out.println("enter day, time, section , doctor , you name in order to book appointment : ");
appointment xx = new appointment();
for (int i=0; i<5; ++i)
xx.setAppDay(input.nextLine());
xx.setAppTime(input.nextLine());
xx.setAppSection(input.nextLine());
xx.setAppDoctor(input.nextLine());
xx.setAppPatient(input.nextLine());
appointments.add(xx);
System.out.println(appointments);
}
public static class appointment {
public String appDay;
public String appTime;
public String appSection;
public String appDoctor;
public String appPatient;
public appointment(String appDay, String appTime, String appSection, String appDoctor, String appPatient) {
this.appDay = appDay;
this.appTime = appTime;
this.appSection = appSection;
this.appDoctor = appDoctor;
this.appPatient = appPatient;
}
public appointment() {
}
public void setAppDay(String appDay) {
this.appDay = appDay;
}
public void setAppTime(String appTime) {
this.appTime = appTime;
}
public void setAppSection(String appSection) {
this.appSection = appSection;
}
public void setAppDoctor(String appDoctor) {
this.appDoctor = appDoctor;
}
public void setAppPatient(String appPatient) {
this.appPatient = appPatient;
}
public String getAppDay() {
return appDay;
}
public String getAppTime() {
return appTime;
}
public String getAppSection() {
return appSection;
}
public String getAppDoctor() {
return appDoctor;
}
public String getAppPatient() {
return appPatient;
}
}
}
Your loop has no braces and you only instantiate one appointment. You wanted something like,
for (int i = 0; i < 5; ++i) {
appointment xx = new appointment();
xx.setAppDay(input.nextLine());
xx.setAppTime(input.nextLine());
xx.setAppSection(input.nextLine());
xx.setAppDoctor(input.nextLine());
xx.setAppPatient(input.nextLine());
appointments.add(xx);
}
Then you need to override toString() in appointment.
Currently the same appointment object is being added to the list, so the list would only have a single entry in it.
So move the object creation and addition to the list along with setting the appointment fields inside the for loop. Please add the curly braces correctly as currently only the
xx.setAppDay(input.nextLine())
is part of the for loop.
Also appointment shouldn't be a static class multiple objects need to be created.
You need to implement a toString() Method for this purpose. And print it like this.
public String toString(){
return this.appDay; // return the output you want, so build a String using your attributes
}
System.out.println(Arrays.toString(appointments));
Edit: And do what Elliott Frisch said.

NullPointer Exception being thrown [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
Ok so I am reading what has already been asking about NPE on here but I can't seem to find anything that will help with my code. It says that It is being thrown at .searchCollection(COLLECTION_NAME).
public class PantryDataStorage {
private static final String COLLECTION_NAME = "pantry";
private static HashMap<String, PantryItem> pantry = getDatabaseItems();
private static String API_KEY = "c3672b0c-b96c-4145-8b75-bd6895b5458e";
private static OrchestrateClient client = new OrchestrateClient(API_KEY);
ShoppingItem shoppingItem = new ShoppingItem();
public static void savePantryItem(String itemName, PantryItem updatedPantryItem){
pantry.put(itemName, updatedPantryItem);
client.kv(COLLECTION_NAME, itemName).put(updatedPantryItem).get().getKey();
}
public static void deletePantryItem(String itemName){
pantry.remove(itemName);
client.kv(COLLECTION_NAME, itemName)
.delete()
.get();
}
public static HashMap<String, PantryItem>getDatabaseItems(){
SearchResults<PantryItem> result = client
.searchCollection(COLLECTION_NAME)
.limit(100)
.get(PantryItem.class, "*")
.get();
Iterator<Result<PantryItem>> iterator = result.getResults().iterator();
HashMap<String, PantryItem> listHash = new HashMap<String, PantryItem>();
while(iterator.hasNext()){
PantryItem pantryitem = iterator.next().getKvObject().getValue();
listHash.put(pantryitem.getItemName(), pantryitem);
}
return listHash;
}
public static boolean itemConsists(String itemName){
pantry.containsKey(itemName);
return true;
}
public static void iteratorMethod(){
Iterator<PantryItem> pantryItemIterator = pantry.values().iterator();
while (pantryItemIterator.hasNext()) {
System.out.println(pantryItemIterator.next());
}
}
}
Starting from savePantryItem you are using client variable and it wasn't declared nor initialized anywhere outside this and other methods as well. Consider declaring client as a private instance variable.

Error with adding to lists with an Integer variable - Java [duplicate]

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?

How to use Arraylist over different classes

Im trying to add a dog (nyHund) which is created in a different class, to an Arraylist i created using a constructor in another class, but whenever i try to use the Arraylist in the "register" class, im getting the error that the arraylist name can't be resolved.
First 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 (ras=="tax"){
return 3.7;
}else{
return ((vikt*ålder)/10);
}
}
public String toString() {
return namn + "\n" + ålder + "\n"+ras+"\n"+vikt+"\n"+getSvanslängd();
}
}
Second Class
import java.util.ArrayList;
public class testning {
public static void main(String[] args) {
Hund nyHund = new Hund("Daisy", 13, "labrador", 22.3);
System.out.println(nyHund.toString());
Register.läggTillHund(nyHund);
}
}
And the Third class:
import java.util.ArrayList;
public class Register {
public static void läggTillHund(Hund nyHund){
hundRegister.add(nyHund);
System.out.println(nyHund);
}
private Register(){
ArrayList<Hund> hundRegister = new ArrayList<Hund>();
}
}
The problem i am experiencing is with "hundRegister.add(nyHund)"
any thoughts? or pointers where im going wrong? (very new at Java)
Best Regards
Oskar
The ArrayList you've created is local to your Register constructor. Declare it inside the class, but outside the constructor, as an instance variable, so it's in scope throughout the class.
public class Register {
private ArrayList<Hund> hundRegister;
private Register(){
hundRegister = new ArrayList<Hund>();
}
}
Additionally, it's unclear why the constructor is private. Nothing else can access that constructor. I would make it public.
Also, in getSvanslängd, replace ras=="tax" with "tax".equals(ras). See How do I compare strings in Java?.

Exception NullPointer, suggestions? [duplicate]

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

Categories