0

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.

3
  • 1
    this == null will always be false Commented Mar 27, 2018 at 14:05
  • And does not work means nothing. Please give exact error. Commented Mar 27, 2018 at 14:06
  • when I print t2 It is supposed to print the whole list. this doesn't work it gives an exception Commented Mar 27, 2018 at 18:09

1 Answer 1

4

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()); } } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.