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 + '}';
}
}
Related
I have a SuperClass and two subclasses.
This two subclasses are used on my ui when i click on a button. I want to create one Estudiante and put it on a list. Estudiante has a lot of attributes inside it so i have toString methods on the subclasses and on the superclass.
I have edited the properties of the setListData so a string is no longer required. The problem is, now when i run the program and i try to add an Estudiante and show it, it gives me the StackOverflowError on the lines of the toString of the subclass and the superclass. I would really appreaciate if someone could try to fix it with my code. Thanks
I havent tried much, i have only changed the method for setting the list in the past but now theorically its fixed.
public class Estudiante extends Persona{
private int numero;
private int semestre;
public Estudiante(String unNombre, int unaCedula, String unMail, int unNumero, int unSemestre) {
super(unNombre,unaCedula,unMail);
this.setNumero(unNumero);
this.setSemestre(unSemestre);
}
The toString() of Estudiante (I didnt posted the get and set methods because i dont think they mattered)
#Override
public String toString(){
return super.toString() + "Numero:" + this.getNumero() + "Semestre: " + this.getSemestre();
}
```
SUPERCLASS TOSTRING (Persona)
#Override
public String toString(){
return toString() + "Nombre"+ this.getNombre() + "Cedula " + this.getCedula() + "Mail " + this.getMail();
}
public Persona(String unNombre, int unaCedula, String unMail){
this.setNombre(unNombre);
this.setCedula(unaCedula);
this.setMail(unMail);
}
This is what i have on the UI
private void BotonCrearEstudianteActionPerformed(java.awt.event.ActionEvent evt) {
Estudiante unEst=new Estudiante(NombreEstudiante.getText(), Integer.parseInt(CedulaEstudiante.getText()),MailEstudiante.getText(), Integer.parseInt(NumeroEstudiante.getText()), Integer.parseInt(SemestreEstudiante.getText()));
modelo.agregarEstudiante(unEst);
ListaEstudiantesJ.setListData(modelo.getListaEstudiantes().toArray());
StackOverflowError on the lines of both toStrings, the one on the subclass and the one in the superclass.
This
public String toString(){
return toString()
+ "Nombre"+ getNombre() + "Cedula " + getCedula() + "Mail " + getMail();
}
calls the overriden toString:
public String toString(){
return super.toString()
+ "Numero:" + getNumero() + "Semestre: " + getSemestre();
}
which again calls the original toString.
Hence and endless loop.
In the base class there are two possiblities:
Only super.toString() is correct:
public String toString(){
return super.toString()
+ "Nombre"+ getNombre() + "Cedula " + getCedula() + "Mail " + getMail();
}
Or simply no toString at all.
public String toString(){
return "Nombre"+ getNombre() + "Cedula " + getCedula() + "Mail " + getMail();
}
I am new to Java - I am trying to understand how to use a "derived" "attribute" in a class. My understanding is that this is basically the same as the typical "full name" use case using a getter in C#, but I want to make sure. In C#, I would write.
public string fullName
{
get {return this.fName + " " + this.lName;}
}
and then call it like this:
Dude homieG = new Dude()
{
fName = "Homie",
lName = "G"
};
Console.WriteLine(homieG.fullName);
https://dotnetfiddle.net/0ppd8j
How do I do this in Java? Googling "derived attribute (or 'property') java" gives me nothing.
Create a method. There are no "properties" in java.
public String getFullBlammy()
{
return firstName + " " + lastName;
}
I want to know how to print a List in Java where in each position there is a String and an int.
List pasajeros = new ArrayList();
I insert the data like this:
public void insert(List a) {
System.out.print("Name: ");
name= sc.nextLine();
System.out.print("Number: ");
number= sc.nextInt();
ClassName aero = new ClassName(name, number);
a.add(aero);
}
}
And it seems to work like this, but in the syso gives me an error.
So you have a list of ClassName.
To print them, you can simply use a for loop:
List<ClassName> pasajeros = new ArrayList<>();
// + insert elements
for (ClassName cn : pasajeros) {
System.out.println("Name: " + cn.getName() + ", number: " + cn.getNumber());
}
You are printing an object without overriding the toString method..
list.Aerolinea#154617c means you are printing the objects hashcode..
so your problem is not at inserting, is at printing out the objects that the list is holding, in this case your Aerolinea class must override properly the toString method.
something like:
class Aerolinea {
private String nombre;
private String apellido;
#Override
public String toString() {
return "Aerolinea [nombre=" + nombre + ", apellido=" + apellido + "]";
}
}
Try like put method toString in your class...
public class Aerolinea {
String nombre;
.......
.......
public String toString() {
return "nombre" = nombre;
}
}
Ok I fixed it finally, it was silly...
I forgot to write < ClassName> in the method. Here is the final code
public void vertodo(List<Aerolinea> a) {
for (Aerolinea cn : a) {
System.out.println("Name: " + cn.name+ " ID: " + cn.id);
}
}
since I had created it like List pasajeros = new ArrayList();, then I changed it to List<Aerolinea> pasajeros = new ArrayList();.
Although I can't write the final <> empty after ArrayList as some have recommended.
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.
}
}
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";