Inner Class - Order of Print Statements - - java

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().

Related

How to print list that I got from findall JpaRepository?

LOG I am getting
Hibernate: select * from resource_hierarchy
com.att.dmp.entity.ResourceHierarchy#7380c27
Instead of com.att.dmp.entity.ResourceHierarchy#7380c27, I want the actual list something like ResourceHieracy [ ID = 1, name = Apple, product = Banana]
List<com.att.dmp.entity.ResourceHierarchy> list = hesourceHierarchyRepository.findAOI();
for(int i=0;i<list.size();i++){
System.out.println(list.get(i));
}
#Repository
public interface ResourceHierarchyRepository extends JpaRepository<ResourceHierarchy, String> {
#Query(value="select * from resource_hierarchy ", nativeQuery=true)
List<ResourceHierarchy> findAOI();
}
When you print something it actually calls the toString() method of the class. If you want to print something else, lets say the variables of class, override the toString() method of ResourceHierarchy class and return the value of variables from the method as String. And it will print your expected values. Something like:
public class ResourceHierarchy {
private String id;
private String name;
private String product;
#Override
public String toString() {
return "ResourceHierarchy[" +
"id = " + id +
"name + " + name +
"product + " + product +
"]";
}
}
Or alternatively you can use lambok to auto-generate toString() code for you.

I dont understand a problem im having with an toString while mixing it with my UI

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();
}

How to print different parts of a List in Java

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.

Checking if an Object has already been Instantiated in Java [duplicate]

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.
}
}

Help with toString() - adding to collections

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";

Categories

Resources