问题描述
我正在编写一个程序来从文本文件(仅包含整数)中获取输入,将其放入链表并显示链表.这是我的代码:
I am writing a program to get input from a text file (only contain integers), put it into linked list and display the linked list. Here is my code:
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;
}
}
}
在我将显示方法更改为静态后,它现在可以工作了.但是在我改成静态之前.错误说非静态方法 display(Node) 不能从 **static 上下文中引用 我阅读了一些关于静态和非静态的文档.要调用非静态,我需要实例化一个实例,然后像 instance.method 一样调用.要调用静态方法,您可以像class.method"一样调用.我的问题是基于我的程序.我没有在其他类中创建方法,为什么要改为静态方法?什么是所谓的静态内容?谢谢你给我解释.
It works now after I changed the display method to be static. However before I changed to static. The error said non-static method display(Node) cannot be referenced from a **static context I read some document about the static and no-static. To call a no-static, I need to instantiate an instance then call like instance.method. To call static method, you can call like "class.method". My question is based on my program. I did not create the method in other class, why I need to change to static method? What is the so called static content? Thank you for explaining it to me.
推荐答案
您的主方法是静态上下文,您正试图从中调用非静态方法 display().即使在同一个班级,那也行不通.要使显示方法非静态,您必须这样做.
Your main-method is the static context, and you are trying to call the non-static method display() from it. That doesn't work even if it is in the same class. To have the disply method non-static you have to do this.
public static void main(String[] args) throws FileNotFoundException{
ReverseLL r = new ReverseLL();
r.display(head);
}
public void display(Node head){
...
}
这篇关于不能从 **静态上下文** 引用非静态方法.这里的静态内容是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!