Depth First Search on graph java
<p>I am having a bit of a problem implementing DFS traversal in java. My problem I think is the 'dfs' method in Graph.java I coded.  It is not returning the required output giving it a specific input. My code is below along with its input and desired output. Could someone help me solve this problem in my code. Thanks.</p>

<p>Graph.java</p>

<pre><code>public class Graph {
ArrayList&lt;Vertex&gt; Vertices=new ArrayList&lt;Vertex&gt;();
Stack&lt;Integer&gt; stack=new Stack&lt;Integer&gt;();
public Graph(){
    Scanner in=new Scanner(System.in);
    String sz=in.nextLine();
    int size=Integer.parseInt(sz);
    for(int i=0; i&lt;size; i++) addVertex();
    String s=in.nextLine();
    while(!s.equals("-1")){
        String[] arr=s.split(",");
        int v1=Integer.parseInt(arr[0]);
        int v2=Integer.parseInt(arr[1]);
        addEdge(v1,v2);
        s=in.nextLine();
    }

    //Vertex v=Vertices.get(2);
    //System.out.println(dfs(v));
}

public static void main(String[] args){
    new Graph();
}
public void addVertex(){
    Vertex v=new Vertex(Vertices.size());
    Vertices.add(v);
}
public Vertex getVertex(int n){
    return Vertices.get(n);
}
public void addEdge(int n, int m){
    Vertex v1=Vertices.get(n);
    Vertex v2=Vertices.get(m);
    v1.addAdjacency(v2);
    v2.addAdjacency(v1);
}
public void dfs(Vertex obj){
    obj.marked=true;
    int k=0;
    for(Vertex v:obj.Vertices){
        Vertex d=v;
        if(!d.marked){
            d.parent=obj;
            k=d.parent.vertexNumber;
            stack.push(k);
            dfs(d);
        }
    }
}
}
</code></pre>

<p>Vertex.java</p>

<pre><code>public class Vertex {
int vertexNumber;
Vertex parent = null;
boolean marked = false;
LinkedList&lt;Vertex&gt; Vertices = new LinkedList&lt;Vertex&gt;();

public Vertex(int num) {
    vertexNumber = num;
}

public void addAdjacency(Vertex object) {
    Vertices.add(object);
}

public boolean isAdjacent(Vertex object) {
    if (Vertices.contains(object))
        return true;
    else
        return false;
}

public int getDegree() {
    return Vertices.size();
}
</code></pre>

<p>}
<a href="https://i.stack.imgur.com/i1fO8.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/i1fO8.jpg" alt="enter image description here"></a></p>