This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I have a problem right now in my program where a Student class is allowed 1 book and it must be stored in a variable _book however I can not seem to find a way to check if an object has already been instantiated or not without getting a run time error.
I have tried
Comparing variable to null
Accessing a function inside the variable that checks if the variable is null
Accessing a function inside the variable that checks if variable is 0
Simplified Code:
Student Class
public class Student {
private String _name;
private Library _collegeLibrary;
private LibraryCard _card;
private TextBook _book;
public Student(String name, Library library) {
_name = name;
_collegeLibrary = library;
System.out.println("[Student] Name: " + _name);
}
public void describe() {
String message;
message = "[Student] " + _name;
if (_book.returnTitle() == null) // returns java.lang.NullPointerException
message += " does not have a book";
else {
message += " is borrowing the book \"" + _book.returnTitle() + "\"";
}
System.out.println(message);
}
}
TextBook Class
public class TextBook {
String _title;
public TextBook(String title) {
_title = title;
}
public String returnTitle() {
return _title;
}
}
The above code will give me a java.lang.NullPointerException. I looked into catching the error however it doesn't seem like that is recommended.
You are checking if _book.returnTitle() is null, however, this doesn't take in account for _book being null. You can check if _book is null instead. That should fix your nullpointer exception.
Also, you should always wrap your if-else clauses in curly brackets. That way it's easier to read.
Change this section of your code:
if (_book.returnTitle() == null) // returns java.lang.NullPointerException
message += " does not have a book";
else {
message += " is borrowing the book \"" + _book.returnTitle() + "\"";
}
To this:
if (_book == null) { // returns java.lang.NullPointerException
message += " does not have a book";
} else {
message += " is borrowing the book \"" + _book.returnTitle() + "\"";
}
Also, as a tip, you can override the toString function to do exactly what your describe function does:
#Override
public String toString() {
String message;
message = "[Student] " + _name;
if (_book == null) { // returns java.lang.NullPointerException
message += " does not have a book";
} else {
message += " is borrowing the book \"" + _book.returnTitle() + "\"";
}
return message;
}
Usage:
public class SomeClass {
public static void main(String[] args) {
Student student = new Student("Student", new Library());
System.out.println(student); //Because you override #toString() you can just println the Student object.
}
}
Related
I have the following problem with displaying an object as a string:
class Gast{
String voorNaam, achterNaam;
datum geboorteDatum;
Gast(String vNaam, String aNaam, datum input){
voorNaam = vNaam;
achterNaam = aNaam;
geboorteDatum = input;
}
public String toString(){
return("Naam: " + voorNaam + " " + achterNaam + " " + geboorteDatum);
}
}
here I implemented a way to represent this object in a string, however when I try to use that in this class:
class Kamer{
boolean vrij;
Gast gast;
Kamer(){}
public String toString(){
if(vrij == true){
return "De kamer is vrij!";
}
else{
return gast;
}
}
}
I get the following error:
kamer.java:17: error: incompatible types: Gast cannot be converted to String
return gast;
I gave a string representation of the object Gast in its class?
Does the other class not inherit the representation I gave?
Try:
return gast.toString();
Edit: Better yet, as suggested by #Andreas comment, use String.valueOf(gast) if there is a possibility gast can be null (or just check for null manually)
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 an array that I need to print, and I've already looked through stackoverflow so I know that I need to use toString so that I don't just print the hashcode, but for some reason it's still printing stuff like "music2.Music2#4162b8ce, music2.Music2#3852fdeb, music2.Music2#509c6c30"
Music2[] musiclist = new Music2[10];
musiclist[0] = new Music2("Pieces of You", "1994", "Jewel");
musiclist[1] = new Music2("Jagged Little Pill", "1995", "Alanis Morissette");
musiclist[2] = new Music2("What If It's You", "1995", "Reba McEntire");
musiclist[3] = new Music2("Misunderstood", "2001", "Pink");
musiclist[4] = new Music2("Laundry Service", "2001", "Shakira");
musiclist[5] = new Music2("Taking the Long Way", "2006", "Dixie Chicks");
musiclist[6] = new Music2("Under My Skin", "2004", "Avril Lavigne");
musiclist[7] = new Music2("Let Go", "2002", "Avril Lavigne");
musiclist[8] = new Music2("Let It Go", "2007", "Tim McGraw");
musiclist[9] = new Music2("White Flag", "2004", "Dido");
public static void printMusic(Music2[] musiclist) {
System.out.println(Arrays.toString(musiclist));
}
This is my array and the method that I am using to print it. Any help would be appreciated.
You should define toString() method in your Music2 class and print it in the way you like. I don't know how fields in your object are named exactly, but it can look like this:
public class Music2 {
...
#Override
public String toString() {
return this.artist + " - "+ this.title + " (" + this.year + ")";
}
}
After that your printMusic method will work as expected.
You can declare a for each loop to display the property of music. This is the code
for (Music2 music : musiclist){
System.out.println("Title: " + music.getTitle);
}
Because by default Arrays got toString() implementation of the Object class, that is:
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
So you need to overwrite toString() in your Class
#Override
public String toString() {
return this.fieldNameone + " "+ this.fieldNametwo + " " + this.fieldNamethree + " ";
}
If using Java8 you can use
Arrays.stream(musiclist).forEach(System.out::print)
but make sure that Music2 has an overriden method for toString()
In the Arrays.toString(musiclist) you are actually invoking toString() on each element of the array to compose the resulting string. So, if you override the basic Object toString() implementation in Music2 class you will get what you want
public class Music2 {
.....
#Override
public String toString() {
return "Music2{" + "title=" + title + ", group=" + group + ", year=" + year + '}';
}
}
Here I am trying to take output like modifier returntype methodname parameter in android listview so when I execute my android project it is not able to display like above I mention. Example:
(public final void wait(long,int))
In this format. Can anyone see what the error happen?
Can anyone tell what went wrong in my code?
public class DisplayM {
public static int i = 0;
public static boolean theEnd;
public static String methodname;
public static String parameter;
public static void main() throws Exception {
Log.i("Ramu", "I am here displayM ");
Class o = Class.forName("android.view.ActionMode");
Method[] methods = o.getMethods();
for (Method method : methods) {
Class retype = method.getReturnType();
int mod = method.getModifiers();
Class retType = null;
Log.i("Ramu", "parameter name " + Modifier.toString(mod) + "
"+retType.getName()
+ " " + method.getName() + "("
);
Class[] paratypes = method.getParameterTypes();
String comma = "";
for (Class paratype : paratypes) {
Log.i(comma + paratype.getName() + retType.getName(), comma);
comma = ",";
}
methodname = methods[i].getName();
Listview.your_array_list.add(methodname);
Log.i("Ramu", "methode name " + methods[i].getName());
Log.i(")", comma);
}
}
}
Class retType = null;
is a very odd assignment, and you have a Class retype that you also do not use but has a valid value. Please use the correct variable name of retype, as in:
Log.i("Ramu","parameter name "+ Modifier.toString(mod) + "
"+retype.getName()
+ " " + method.getName() + "(");
You should use a debugger first to see where things are null or otherwise faulty, especially in more complex code.
I'm puzzled as to why my program prints statements in a certain order?
I have a Student class, inside which is an Inner Class of Address. The idea of the program is to first assign a Home Address to a Student Object, but then also assign a University / Term Time Address by utilizing the Inner Address Class.
The code is as follows:
Student Class (with Inner Address Class)
public class Student {
private String name;
private Address homeAddress, uniAddress;
public Student(String name, int houseNumber, String homeStreet) {
this.name = name;
homeAddress = new Address(houseNumber, homeStreet);
}
public String getName() {
return name;
}
public Address getHomeAddress() {
String s = "n/a";
if (homeAddress != null) {
return homeAddress;
} else {
// System.out.println(s);
return null;
}
}
public void setUniAddress(int num, String add) {
uniAddress = new Address(num, add);
}
public Address getUniAddress() {
String s = "n/aa";
//If uniAddress isn't set,
// then "n/aa" gets printed before anything else i/e toString() method - WHY?
if (uniAddress == null) {
System.out.println(s);
return null;
} else {
return uniAddress;
}
}
#Override
public String toString() {
return "NAME: " + getName() + "\n"
+ "HOME ADDRESS: " + getHomeAddress() + "\n"
+ "TERM TIME ADDRESS: " + getUniAddress();
}
// Inner Class
public class Address {
private int number;
private String street;
public Address(int no, String street) {
number = no;
this.street = street;
}
#Override
public String toString() {
//return name + "\n" + number + " " + street;
return number + " " + street;
}
}
} // more Student methods .. }
The TestStudent Class (with main method)
public class TestStudent {
public static void main(String[] args) {
//Home Address
Student s1 = new Student("Cathy", 21, "Smithfield Drive");
//Uni Address
s1.setUniAddress(72, "Nottingham Drive");
Student.Address anotherAddress = s1.new Address(8, "Deerfield Way");
// note the use of new
System.out.println(s1.toString());
}
}
The output is:
n/aa
NAME: Cathy
HOME ADDRESS: 21 Smithfield Drive
TERM TIME ADDRESS: null
(all on new lines)
If I do not assign a Uni Address to the Student (i.e. If I comment out the appropriate line in the main method - that calls the setUniAddress() method), I am curious then, as to why 'n/aa' from the getUniAddress() method is printed before the toString() method? (as above)
If I do call the setUniAddress() method the out put is:
NAME: Cathy
HOME ADDRESS: 21 Smithfield Drive
TERM TIME ADDRESS: 72 Nottingham Drive
(all on new lines)
Which seems to work as intended.
I'm also wondering how, instead of printing 'null' to the TERM TIME ADDRESS: (when setUniAddress() method isn't called), I could return the 'n/aa' in it's place - that is what I was attempting to do?
Thanks.
getUniAddress() is called from the toString() which is why the n/aa is printed first.
If you want to print "n/aa" as a default value - set it as a default value, for example, change the declaration to:
private Address homeAddress, uniAddress = "n/aa";
#Override
public String toString() {
return "NAME: " + getName() + "\n"
+ "HOME ADDRESS: " + getHomeAddress() + "\n"
+ "TERM TIME ADDRESS: " + getUniAddress(); // <-- here you call getUniAddress() which
// is why "n/aa" is printed first
}
in getUniAddress() you have the following line which prints "n/aa":
System.out.println(s);
When the return statement in the toString() method is executed the get*() methods are called. Then a string is created and returned by the toString() method.
So the 'n/aa' is printed while calculating the string to return from the toString(), then the toString() method returns the string and the main method prints the output generated from toString().
I am adding information from main()
I am adding different information for CD, DVD, book..
I have 3 separate classes - item has 3 classes in it...
project - main()
Library - this function does all the adding
Item(cd,dvd,book) inheritance
For Music i am adding band info, title info, keywords, and members..
I am adding members separately than of the other info..
As you can see the members is not outputing correctly as the others..
>>> music CDs:
-Music-
band: Jerry Garcia Band
# songs: 15
members: [Ljava.lang.String;#61de33
title: Don't Let Go
C:\Java\a03>
I am using the same toString() function for members as i am the rest, so i am not sure why it would do this..
I will give you as much info as i think you need to see..
Main() - as you can see it calls 2 different functions.
the addbandmembers is where i am having problems...
out.println(">>> adding items to library:\n");
item = library.addMusicCD("Europe In '72", "Grateful Dead", 12, "acid rock", "sixties", "jam bands");
if (item != null) {
library.addBandMembers(item, "Jerry Garcia", "Bill Kreutzman", "Keith Godcheaux");
library.printItem(out, item);
}
in Library class - here is the addbandmember function ..
Could this be the cause??
public void addBandMembers(Item musicCD, String... members)
{
((CD)musicCD).addband(members);
}
In the Items class here is the function addband - tostring()
here is the CD class which extends the items class..
class Item
{
private String title;
public String toString()
{
String line1 = "title: " + title + "\n";
return line1;
}
public void print()
{
System.out.println(toString());
}
public Item()
{}
public Item(String theTitle)
{
title = theTitle;
}
public String getTitle()
{
return title;
}
}
class CD extends Item
{
private String artist;
private String [] members;
private int number;
public CD(String theTitle, String theBand, int Snumber, String... keywords)
{
super(theTitle);
this.artist = theBand;
this.number = Snumber;
}
public void addband(String... member)
{
this.members = member;
}
public String getArtist()
{
return artist;
}
public String [] getMembers()
{
return members;
}
public String toString()
{
return "-Music-" + "\n" + "band: " + artist + "\n" + "# songs: " + number + "\n" + "members: " + members + "\n" + "\n" + super.toString() + "\n";
}
public void print()
{
System.out.println(toString());
}
}
I do have other information in the items class like a nook class, movie class that i didnt show. I would like to keep everything the way i have it set up..
So, if the other items are printing fine than maybe its the cast in the addbandmember function thats giving me problems?
members is printing the way it is since it's an array (you can tell this by the fact its output as members: [Ljava.lang.String;#61de33 ).
Instead you need to iterate through it and print each element.
e.g.
for (String member : members) {
...
}
The simplest way is to use Arrays.toString(). Alternatively append to a StringBuilder and then print to this. You can be cleverer, and use StringUtils.join() from Apache Commons Lang, which will give you more control.
Arrays don't have a useful toString() implementation. You can print out the members in a loop or use the Arrays.toString() method to do this for you:
return "-Music-" + "\n"
+ "band: " + artist + "\n"
+ "# songs: " + number + "\n"
+ "members: " + Arrays.toString(members) + "\n"
+ "\n"
+ super.toString() + "\n";