使用.nextInt()时出错 [英] Getting error while using .nextInt()

查看:97
本文介绍了使用.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆