使用.nextInt()时出错 [英] Getting error while using .nextInt()
问题描述
我收到此错误:每次尝试执行其中包含.nextInt()
的代码行时,都无法对非静态字段进行静态引用" .
I am getting this error: "cannot make a static reference to the nonstatic field" everytime I try to execute a line of code with .nextInt()
in it.
以下是可能影响(我能想到的)的代码行:
Here are the lines of code that could affect (that I can think of):
private Scanner input = new Scanner(System.in);
int priceLocation = input.nextInt();
推荐答案
这很可能是因为您试图以静态方法访问input
,我认为它是main()
方法.像这样
This is most likely because you're trying to access input
in a static method, which I'm assuming it to be the main()
method. Something like this
private Scanner input = new Scanner(System.in);
public static void main(String[] args) {
int priceLocation = input.nextInt(); // This is not allowed as input is not static
您需要将input
设置为static
,或者可以将其移动到static
( main )方法中.
You need to either make your input
as static
or may be move it inside the static
(main) method.
解决方案1::将input
设置为static
.
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
int priceLocation = input.nextInt();
解决方案2::将input
移至主体内部(请注意,如果将input
移至main()
内,则不能在任何其他方法中使用input
.本地).
Solution2: Move the input
inside the main(note that you can't use input
in any other methods, if its moved inside the main()
, as it'll be local to it).
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int priceLocation = input.nextInt();
这篇关于使用.nextInt()时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!