2016-11-04 80 views
-4

我正在写一个程序从文本文件中获取输入(只包含整数),将其放入链接列表并显示链接列表。这里是我的代码:非静态方法不能从**静态上下文**中引用。什么是静态内容?

import java.util.Scanner; 
import java.io.File; 
import java.io.FileNotFoundException; 

class Node{ 
    int value; 
    Node next; 
    Node(){ 
     next = null; 
    } 
} 


public class ReverseLL{ 
    public static void main(String[] args) throws FileNotFoundException{ 
     Scanner in = new Scanner(new File("input.txt")); 
     Node head = null; 
     Node tail = null; 
     while(in.hasNextInt()){ 
      Node ptr = new Node(); 
      ptr.value = in.nextInt(); 
      if(head == null){ 
       head = ptr; 
       tail = ptr; 
      }else{ 
       tail.next = ptr; 
      } 
      tail = ptr; 
     } 
     display(head); 
     in.close(); 
    } 

    static void display(Node head){ 
     while(head!=null){ 
      System.out.print(head.value + " " + "\n"); 
      head = head.next; 
     } 
    } 

} 

它现在以后,我改变了显示器的方法是静态。然而在我改变为静态之前。该错误说非静态方法显示(节点)不能从静态上下文引用我读了一些关于静态和无静态的文档。要调用一个非静态的,我需要实例化一个实例,然后调用像instance.method。要调用静态方法,你可以调用像“class.method”。我的问题是基于我的程序。我没有在其他类中创建该方法,为什么我需要更改为静态方法?什么是所谓的静态内容?谢谢你向我解释。

+0

public ** static ** void main(String [] args)。 – DimaSan

+0

@ 1615903我在问另外一个。 – Jeffery

+1

@Jeffery它是一个完整的重复,并解释了为什么编译器不会在那里编译。 – SomeJavaGuy

回答

2

您的主要方法是静态上下文,并且您试图从中调用非静态方法display()。即使它属于同一班级,也不起作用。要使disply方法非静态,你必须这样做。

public static void main(String[] args) throws FileNotFoundException{ 
    ReverseLL r = new ReverseLL(); 
    r.display(head); 

} 

public void display(Node head){ 
    ... 
} 
0

调用的静态上下文:

Class_Name.method_name(); 

调用的非静态背景:

Class_Name object_name = new Class_Name(); 
object_name.method_name(); 

你不应该叫非静态方法使用静态上下文,反之亦然。

0

您正在致电public static void main(String[] args)方法的display方法。

要解决其静态方法,你可以这样做:

public class ReverseLL{ 

    public void run() throws FileNotFoundException{ 
     Scanner in = new Scanner(new File("input.txt")); 
     Node head = null; 
     Node tail = null; 
     while(in.hasNextInt()){ 
      Node ptr = new Node(); 
      ptr.value = in.nextInt(); 
      if(head == null){ 
       head = ptr; 
       tail = ptr; 
      }else{ 
       tail.next = ptr; 
      } 
      tail = ptr; 
     } 
     display(head); 
     in.close(); 
    } 

    void display(Node head){ 
     while(head!=null){ 
      System.out.print(head.value + " " + "\n"); 
      head = head.next; 
     } 
    } 

    public static void main(String[] args){ 
     ReverseLL reverseLL = new ReverseLL(); 
     try{ 
      reverseLL.run(); 
     }catch(FileNotFoundException e){ 
      // handle ex... 
     }  
    } 
} 
0

,您还可以使用新的ReverseLL()dislpay(头);它将深挖问题。

相关问题