why am i getting a NullPointerException Java [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
So im writing a Java programming, I have 2 classes, and a class test that uses these 2 classes. running eclipseIDE, it keeps telling me i have a NullPointerException at the "s+=c.getName() + " " +... "
this is a method in Student.
public String getCourses()
{
String s = "";
for(Course c: this.courses)
{
s+=c.getName() + " " + c.getID() + " " + c.getScore(this.id);
s+="\n";
}
return s;
}
it calls this method that is in the Course class.
public String getID()
{
return this.id;
}
i tried only doing getName(); it had no issue, however once i added getID() it became an issue. getName is the same type of code, it returns the "name" of the object as a string.
name and id is "initialized" via a constructor
Stacktrace:
Exception in thread "main" java.lang.NullPointerException
at hw6.Student.getCourses(Student.java:47)
at hw6.CourseStudent_test.main(CourseStudent_test.java:100)
this is the getScore method
public double getScore(String id)
{
int i = 0;
for(; i < this.students.length;i++)
{
if(this.students[i].getID() == id )
{
break;
}
}
return this.scores[i];
}

If the exception is occurring where your stacktrace + question says it is, then one of the elements in courses must be null.
Reasoning:
If the exception was thrown inside one of the Course method calls, then the stacktrace would show that method as the top stack frame.
If one of those 3 calls returned null, you wouldn't get an NPE. You would just get "null" in the resulting concatenation; see String concatenation with Null.

Found the issue, Because of the "For each " loop, when it gets to an Null object, it tries to run the getter methods, however each time it returns null, as there is no "value" for each variable within that object, so i just added a if condition to check if the object is "null"

Related

NullPointerException error when trying to add to ArrayList [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
Trying to add the object member to the ArrayList loggedInList when logging into the Website class.
public class Website
{
// The name of the website.
private String name;
// The number of hits on the website.
public int hits;
// The amount of money taken at the checkout.
private double salesTotal;
//
private ArrayList<Member> loggedInList;
Is the code for my Website class.
public Website(String newName)
{
// Intialises the name of the website.
name = newName;
// Intialises the number of hits on the site.
hits = 0;
// Intialises the amount of money taken at the checkout.
salesTotal = 0;
//
loggedInList = new ArrayList<Member>();
}
Is the constructor for the Website class.
public void memberLogin(Member member)
{
member.setLoginStatus(true);
member.setWebsite(this);
System.out.println(name + " welcomes member " + member.getMembershipNumber() + "," + " you are now logged in.");
member.setWebsite(this);
hits +=1;
loggedInList.add(member);
}
Is the method which SHOULD add the current member into the ArrayList.
The error I get is a NullPointerException on the line:
loggedInList.add(member);
I honestly have no clue why.
I believe you are not using the correct constructor. You may have a default no arg constructor in your code.
In any case, you should do it similar to the code below.
Website website = new Website ("someString value");
website.memberLogin (objectCreatedMember);

Get the name of a null field in Android [duplicate]

This question already has answers here:
How to test whether the value of a Java field gotten by reflection is null?
(4 answers)
Closed 5 years ago.
I have a huge class with members, and i want to check on each member if its null. I don't want to add it manually, just run a for loop (or something similar) which will go over all the fields without 'human' addition every time a field is added.
So far, i can go over the fields, and receive the name of the fields (which is what i need). However, there's nothing on Field that checks if the value of it is null.
Here's what i have so far :
private class Test {
String name1 = null;
String name2 = "test";
String name3 = null;
}
Test mainTest = new Test();
for (Field field : mainTest.getClass().getDeclaredFields()) {
if (field.isValueNull())
Log.i("test", field.getName() + " is missing ");
}
field.isValueNull() -> this is the method i'm looking for.
In this example, the print will be :
name1 is missing
name3 is missing
You can use the get() method of the Field object:
Test mainTest = new Test();
for (Field field : mainTest.getClass().getDeclaredFields()) {
if (field.get(mainTest) == null)
Log.i("test", field.getName() + " is missing ");
}

How to print List's object elements in Java? [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 6 years ago.
I have something like the following:
List<Interval> intervals = new LinkedList<Interval>();
intervals.add(new Interval(1));
intervals.add(new Interval(2));
How can I print the List intervals? I attempted System.out.println(intervals), but it simply returns [Interval#...].
Thank you
The issue is not in printing the List but in printing the Interval.
Implement Interval.toString() method.
System.out.println(intervals) will call .toString() method of the object you are trying to print, which is List.
In order to print every object you have to override the toString() method for Interval or print specific value.
for (Inteval interval : intervals) { System.out.println(interval.getValue());}
or if you override the toString() method for Interval
for (Inteval interval : intervals) { System.out.println(interval);}
You can override the toString() as follows:
public class Interval {
public int value;
public String val;
#Override
public String toString() {
return "Value string: " + val + " value int: " + value;
}
}

Array prints memory address despite Override [duplicate]

This question already has answers here:
I am getting the memory address from an arraylist, need info
(2 answers)
Closed 8 years ago.
Now, I want it to only print what it says, without the memory address as well. How would I achieve that?
public Telefonnummer[] getTelenummer() {
Telefonnummer[] tnummer = new Telefonnummer[nummerarray.size()];
nummerarray.toArray(tnummer);
System.out.println(Arrays.toString(tnummer) );
return tnummer;
}
Is the constructor and:
private static void kundSök() {
System.out.println("...? ");
String namn = keyboard.nextLine();
if (kunderna.containsKey(namn)) {
for (String k : kunderna.keySet()) {
Kund kund = kunderna.get(k);
System.out.println(kund);
System.out.println(kund.getTelenummer());
After i have added a person to the ArrayList etc it gives me an output of:
Sam wasdfgn
[123456: efdg]
[LTelefonnummer;#28d93b30
The last part, memory address bit, is the part I want to get rid of.
Yet again, how do i achieve that?
Edit: I tried to Override, but it did not do anything at all. Could there be another problem?
The default behaviour for toString is to print the type name (as L followed by the type name), followed by # and the hexString of the hashCode (which by default is the memory address for the object).
To change this, override the toString method for your Telefonnummer class.
public class Telefonnummer {
private String nummer;
...
#Override public String toString() {
return "Dial " + nummer + " for a good time";
}
}
Guava library has Joiner which can be used for that. See https://code.google.com/p/guava-libraries/wiki/StringsExplained
String str = Joiner.on(",").join(list);
You also have to have working toString function on class for elements of the list

Print Array of Objects in BlueJ [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 6 years ago.
For an assignment, I was asked to work on calling a class and creating an array objects, which i did here;
public void DVDArrayObjects() {
//creates variables
int i;
DVDClass[] dvdArray = new DVDClass[5];
//reference to DVDClass
for (i = 0; i < 2; i ++) {
//create new instance of calling the class
dvdArray[i] = new DVDClass();
//create new instance of getting the info
dvdArray[i].getDVDInfo();
//display
//System.out.println(dvdArray[i]);
}
}
Creating the array of objects works fine, but displaying doesn't. it shows the memory allocation when i run it. I'm really stuck as to how to get it to display.
** EDIT **
When i use System.out.println(dvdArray[i].getDVDInfo()); the error void types not allowed in here shows up
** END OF EDIT **
Any help at all would be greatly appreciated.
Print the DVD info (assuming that it returns a string).
System.out.println(dvdArray[i].getDVDInfo());
If it doesn't return a string, you need to override the toString() method on the class DVDInfo like this.
#Override
public String toString()
{
return "Film Name\t: " + filmName +
"\nFilm Director\t: " + filmDirector +
"\nRun Time\t: " + runTime +
"\nLead Actor\t: " + leadActor;
}
Hope this helps.
You need to override the toString() method.
public class DVDCLass {
#Override
public String toString(){
return // whatever you want the output to be
}
}
Override toString() method in your DVDClass class
do like below
class DVDClass{
public String toString(){
return // whatever you want the output to be
}
}

Categories