0

i have problem with the error ( non-static variable this cannot be referenced from a static context )

** I can't post an image because i need 10 reputation :(

my code solves this problem :

Write a Java function Sum2List that takes two lists L1 and L2 of the same size and returns list L that contains the sum of data inside the corresponding nodes of lists L1 and L2.

and this is the whole code , but i can'n test it because of the above error

public class listNode {
    int data;
    listNode next;

    listNode(int d, listNode n){
       data = d;
       next = n;
    }
 }

public class list {
   listNode first;
}

public list Sum2List (list l1 , list l2){
    list l = new list();
    listNode lNode = new listNode(0,null);
    l.first = lNode;

    listNode p = l1.first;
    listNode q = l2.first;

    for (p = l1.first; p.next!=null; p=p.next,q=q.next){
        lNode.data = p.data + q.data;

        if (p.next != null)
            lNode.next = new listNode(0,null);
    }
    return l;
}


public static void main (String[] args){

    list l1= new list();
    listNode node4 = new listNode(4,null);
    listNode node3 = new listNode(3,node4);
    listNode node2 = new listNode(2,node3);
    listNode node1 = new listNode(1,node2);

    l1.first = node1;

    list l2= new list();
    listNode node8 = new listNode(8,null);
    listNode node7 = new listNode(7,node8);
    listNode node6 = new listNode(6,node7);
    listNode node5 = new listNode(5,node6);

    l2.first = node5;

    list l = Sum2List(l1,l2);

    for(listNode p = l.first; p.next !=null; p=p.next){
        System.out.println(p.data);
    }
}
Nivas
  • 18,126
  • 4
  • 62
  • 76

1 Answers1

0
public list Sum2List (list l1 , list l2){

This needs to be marked static. You cannot call an instance method from a static method without an instance of that class. If you just think about it, you'll realize it won't make sense. An instance method belongs to a single instantiation of a class, so it requires an instance to exist to be called.

Kon
  • 10,702
  • 6
  • 41
  • 58