2

I try to make an array of nodes with a node on a specific place in the array.

For example:
I add a node in the array and set its number to 1.
I add another node in the array on the next position and set its number to 2.
Both nodes got the number 2 now.

Sample of the code:

public static String run(InputStream in) {

    Scanner sc = new Scanner(in);

    //indicating values
    sc.nextInt(); /* int vertices = */
    int edge = sc.nextInt();
    int start = sc.nextInt();
    int end = sc.nextInt();

    if (start == end) {
        sc.close();
        Path = "yes";
    } else {
        nodes = new Node[edge + 1];
        for (int i = 1; i < edge; i++) {

            //Node values
            int number = sc.nextInt();
            int next = sc.nextInt();
            sc.nextInt(); /* int distance = */

            Node node = new Node(number, next);

            if (nodes[number] == null) {
                nodes[number] = (node);
            } else {
                nodes[number].addChild(next);
            }
        }
        hasPath(nodes[start], end);

    }
    sc.close();

    return Path;
}

Sample of the Node code:

import java.util.ArrayList;

public class Node {

private ArrayList<Integer> childs = new ArrayList<Integer>();

private static int number;

public Node(int n, int next){
    number = n;
    childs.add(next);
}

public int getNumber(){
    return number;
}

public void addChild(int child){
    childs.add(child);
}  

Can anyone please help me?

1 Answer 1

3

The problem is with declaring the number member static. This means there's only one such member for the Node class, instead of each instance having its own member. Just define it as an instance variable, and you should be fine:

public class Node {
    private ArrayList<Integer> childs = new ArrayList<Integer>();
    private int number; // Note the static was removed
    // rest of the class
Sign up to request clarification or add additional context in comments.

2 Comments

That did the job, thnx!
@EmielRietdijk: If this solved your problem you should mark it as "Accepted"!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.