错误:无法从Java中的静态上下文引用非静态变量扫描

时间:2013-10-22 08:52:22

标签: java syntax-error

import java.util.Scanner;

public class CHP4Ex
    {
        Scanner scan = new Scanner(System.in);
        public static void main(String[] args)
        {
            System.out.println("enter a n: ");
            int n = scan.nextInt();
            int i=10;
            while (i<n)
            {
                System.out.println(i);
                i = i + 10;
            }
        }
}

为什么我收到此错误?我基本上写了一个while循环,打印所有可被10整除且小于n的正数。例如,如果n为100,请输入10 ... 90。

2 个答案:

答案 0 :(得分:5)

将Scanner类对象放在main函数中。基本上问题是您的代码违反了静态功能。你不能在静态函数中使用非静态成员,main在你的情况下是静态的。所以它应该是:

import java.util.Scanner;

public class CHP4Ex
    {

        public static void main(String[] args)
        {
            Scanner scan = new Scanner(System.in);
            System.out.println("enter a n: ");
            int n = scan.nextInt();
            int i=10;
            while (i<n)
            {
                System.out.println(i);
                i = i + 10;
            }
        }
}

答案 1 :(得分:0)

您无法在静态上下文中引用非静态变量,因此请更改

Scanner scan = new Scanner(System.in);

private static Scanner scan = new Scanner(System.in);它应该有用