Can objects inherit string representations? - java

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)

Related

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

android: Trying output like modifier returntype methodname parameter in android visible format

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.

Inner Class - Order of Print Statements -

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

Categories

Resources