【发布时间】:2016-11-04 07:31:10
【问题描述】:
我正在编写一个程序来从文本文件(仅包含整数)中获取输入,将其放入链表并显示链表。这是我的代码:
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;
}
}
}
在我将显示方法更改为静态后,它现在可以工作了。但是在我改为静态之前。错误说 non-static method display(Node) cannot be referenced from a **static context 我阅读了一些关于静态和非静态的文档。要调用非静态,我需要实例化一个实例,然后调用类似 instance.method。要调用静态方法,您可以像“class.method”一样调用。我的问题是基于我的程序。我没有在其他类中创建方法,为什么我需要更改为静态方法?什么是所谓的静态内容?谢谢你给我解释。
【问题讨论】:
-
public static void main (String[] args).
-
@1615903 我问的是另一个。
-
@Jeffery 这是一个完整的副本,并解释了为什么编译器不会在那里编译。
-
@KevinEsche 静态上下文是什么意思?
标签: java static-methods