Why do I get "The method createLL() is undefined for the type LinkedListUse" error when calling from same package in Java?

36 views Asked by At

Class linkedListUse

package linkedlists;

public class LinkedListUse {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        
        Node head=createLL();
        printLL(head);
    }

}

Class CreateAndPrintLL

package linkedlists;

import java.util.Scanner;

public class CreateAndPrintLL {
    
    public Node createLL() {
        Scanner sc=new Scanner(System.in);
        int data=sc.nextInt();
        Node head=null;
        while (data!=-1) {
            Node currentNode=new Node(data);
            if(head==null) {
                head=currentNode;
            }
            else {
                Node tail=head;
                while(tail.next!=null) {
                    tail=tail.next;
                }
                tail.next=currentNode;
            }
            data=sc.nextInt();
        }
        return head;
    }
    
    public void printLL(Node head) {
        Node temp=head;
        while(temp!=null) {
            System.out.print(temp.next);
        }
        System.out.println();
    }
    
}

I'm facing error in my code, int main method i'm trying to call createLL method but it's showing me-The method createLL() is undefined for the type LinkedListUse error inspite of bioth the classes being in the same package....WHY IS THAT?

1

There are 1 answers

0
trincot On

Your main method is trying to access methods of another class. You would need to create an instance of CreateAndPrintLL and call the methods in that instance:

    public static void main(String[] args) {
        CreateAndPrintLL ll = new CreateAndPrintLL();
        Node head = ll.createLL();
        ll.printLL(head);
    }

There is an unrelated error in your CreateAndPrintLL class, in the printLL method: the loop doesn't modify temp, so once it makes an iteration it will keep making more iterations without end.

Fix it like this:

    public void printLL(Node head) {
        Node temp=head;
        while(temp!=null) {
            System.out.print(temp.data); // Depends on how Node exposes data
            temp = temp.next;            // Must move to the next node
        }
        System.out.println();
    }

NB: As I didn't see the Node class I made the assumption that a node's data is accessed via a data instance variable. Adapt if needed.