Reputation: 81
I am new to Java and trying to implement a simple linked list in Java(I know there is a special class for that) and having a problem in the toString() method for the class Tour which is not working. it's suppose to be a recursive method.
public class Tour {
private Ville city;
private Tour suivant;
public Ville getVille() {
return(city);
}
public Tour getSuivant() {
return(suivant);
}
public void setVille(Ville laVille) {
city = laVille;
}
public void setSuivant( Tour leSuivant) {
suivant = leSuivant;
}
public String toString(){
if(this == null) {
return("Fin");
} else {
return(city.toString()+"->" + this.suivant.toString());
}
}
}
the main method is here:
public class Test {
public static void main(String[] args) {
Ville v1 = new Ville();
v1.setNom("tantan");
v1.setCoordonner(1,5);
Ville v2 = new Ville();
v2.setNom("Errachidia");
v2.setCoordonner(10,6);
Tour t1 = new Tour();
t1.setVille(v1);
t1.setSuivant(null);
Tour t2 = new Tour();
t2.setVille(v2);
t2.setSuivant(t1);
System.out.println(t2);
}
}
Thanks in advance.
Upvotes: 0
Views: 102
Reputation: 914
You need to change the if condition. It must terminate before you enter null, not after.
public String toString(){
if(this.suivant == null)
return(city.toString() + "Fin");
else{
return(city.toString()+"->" + this.suivant.toString());
}
}
Upvotes: 4