【问题标题】:Cant call method from another class?不能从另一个类调用方法?
【发布时间】:2019-03-31 03:33:53
【问题描述】:

所以我正在练习链表,我有三个类,一个是 Node 类,一个是 LinkedList 类,另一个是我只需要测试的 main 类。

在我的 LinkedList 类中,我有一个 insert 方法,但是当我尝试在我的类中使用 main 调用 insert 方法时,它无法识别它并显示无法解析方法 insert(int)

这是我的 Node 类的代码

public class Node {
int data;
Node next;

}

public class LinkedList {

Node top;

public void insert(int data){
     Node node = new Node();
     node.data = data;
     node.next = null;

     if(top == null){       
         top = node;
     }
     else{
         Node n = top;   
         while (n.next != null ){ 
             n = n.next; 

         }
         n.next = node;
     }
}

这是我的主要方法,我尝试调用 insert 方法,但它不会让我这样做。

public class Runner {


public static void main(String [] args){

    LinkedList list = new LinkedList();
    list.insert(5);

}

【问题讨论】:

    标签: java methods linked-list


    【解决方案1】:

    您看到这个是因为您已导入 java.util.LinkedList 来代替您自定义的 LinkedList 类。

    您可以导入您的LinkedList 类并从java.util.LinkedList 中删除导入,或者使用LinkedList 的完全限定名称。例如:

    package.of.custom.LinkedList list = new package.of.custom.LinkedList();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-17
      • 1970-01-01
      • 1970-01-01
      • 2014-02-07
      • 1970-01-01
      • 2011-09-09
      相关资源
      最近更新 更多