为什么会出现此错误 [英] Why this error is showing
本文介绍了为什么会出现此错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
public class Test {
String name ;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
name =sc.next();
}
}
在此代码中,错误显示在
In this code the error is showing Under
name =sc.next();
此行
但是当我将变量类型更改为
this line
but when i change variable type to
static String name
错误消失了你能帮助我的原因
我的尝试:
the error is gone what is the reason can you help me
What I have tried:
public class Test {
static String name ;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
name =sc.next();
}
}
推荐答案
因为类(即static
)方法可以访问类变量。
另一方面,类方法不能访问对象(即实例,即非静态)变量。
你可以写,
Because class (i.e.static
) methods have access to class variables.
On the other hand, class methods cannot access object (i.e. instance, i.e. not static) variables.
You might write, as well
import java.util.Scanner;
public class Test
{
String name ;
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
Test test = new Test();
test.name = sc.next();
}
}
再次,我强烈建议您阅读的优秀教程Java OOP
。
请参阅 Java™教程 [ ^ ]
这篇关于为什么会出现此错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文