非静态变量不能从静态上下文引用 [英] Non-static variable cannot be referenced from a static context

查看:236
本文介绍了非静态变量不能从静态上下文引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我第一次被教得不好,所以我还是不明白 static 的一切。

I was taught poorly at first, and so I still don't understand everything about static.

我的错误是我声明的每一个变量,然后尝试使用后面的方法,我得到非静态变量不能...错误。

My error is with every single variable that I declare and then try to use later inside my methods, I get the "non-static variable cannot ..." error.

我可以简单地把我的方法的所有粗略的编码在我的case,它的工作,但是我不能使用递归。

I can simply put all the rough coding of my methods inside my cases, and it works, but then I cannot use recursion.

我真正需要的是一个人帮助语法和指向我如何让我的方法识别我的变量在顶部,如 compareCount 等的正确方向:

What I really need is someone to help on the syntax and point me on the right direction of how to have my methods recognize my variables at the top, like compareCount, etc.:

public class MyProgram7 {
    public static void main (String[]args) throws IOException{
        Scanner scan = new Scanner(System.in);
        int compareCount = 0;
        int low = 0;
        int high = 0;
        int mid = 0;
        int key = 0;
        Scanner temp;
        int[]list;
        String menu, outputString;
        int option = 1;
        boolean found = false;

        // Prompt the user to select an option

        menu = "\n\t1  Reads file" +
               "\n\t2  Finds a specific number in the list" +
               "\n\t3  Prints how many comparisons were needed" +
               "\n\t0  Quit\n\n\n";

        System.out.println(menu);
        System.out.print("\tEnter your selection:   ");
        option = scan.nextInt();

        // Keep reading data until the user enters 0
        while (option != 0) {
            switch (option) {

                case 1:
                   readFile();
                  break;

                case 2:
                   findKey(list,low,high,key);
                  break;

                case 3:
                   printCount();
                  break;

                default: outputString = "\nInvalid Selection\n";
                      System.out.println(outputString);
                      break;
            } // End of switch

            System.out.println(menu);
            System.out.print("\tEnter your selection:   ");
            option = scan.nextInt();
        } // End of while
    } // End of main


    public static void readFile() {
        int i = 0;
        temp = new Scanner(new File("CS1302_Data7_2010.txt"));

        while(temp.hasNext()) {
            list[i]= temp.nextInt();
            i++;
        } //End of while

        temp.close();
        System.out.println("File Found...");
    } // End of readFile()

    public static void findKey() {
        while (found!=true) {
            while (key < 100 || key > 999) {
                System.out.println("Please enter the number you would like to search for? ie 350: ");
                key = scan.nextInt();
            } // End of inside while

            // Base
            if (low <= high) {
                mid = ((low+high)/2);
                if (key == list[mid]) {
                    found = true;
                    compareCount++;
                } // End of inside if
            } // End of outside if
            else
                if (key < list[mid]) {
                    compareCount++;
                    high = mid-1;
                    findKey(list,low,high,key);
                } // End of else if
                else {
                    compareCount++;
                    low = mid+1;
                    findKey(list,low,high,key);
                } // End of else
        } // End of outside while
    } // End of findKey()


    public static void printCount() {
        System.out.println("Total number of comparisons is: " + compareCount);
    } // End of printCount

} // End of class


推荐答案

您必须理解类和该类的实例之间的区别。如果你在街上看到一辆汽车,你立即知道这是一辆汽车,即使你看不到哪个型号或类型。这是因为您将看到的内容与car进行比较。类包含类似于所有汽车。

You must understand the difference between a class and an instance of that class. If you see a car on the street, you know immediately that it's a car even if you can't see which model or type. This is because you compare what you see with the class "car". The class contains which is similar to all cars. Think of it as a template or an idea.

同时,你看到的汽车是car类的一个实例,因为它具有所有属性你希望:有人驾驶它,它有一个引擎,轮子。

At the same time, the car you see is an instance of the class "car" since it has all the properties which you expect: There is someone driving it, it has an engine, wheels.

所以类说所有车都有颜色,实例说这个特定的车是红色。

So the class says "all cars have a color" and the instance says "this specific car is red".

在OO世界中,定义类并在类内部定义 Color 。当类被实例化时(当你创建一个特定的实例),内存是为颜色保留的,你可以给这个特定的实例一种颜色。由于这些属性是特定的,因此它们是非静态的。

In the OO world, you define the class and inside the class, you define a field of type Color. When the class is instantiated (when you create a specific instance), memory is reserved for the color and you can give this specific instance a color. Since these attributes are specific, they are non-static.

静态字段和方法与所有实例共享。它们用于特定于类而不是特定实例的值。对于方法,这通常是全局辅助方法(如 Integer.parseInt())。对于字段,它通常是常数(如汽车类型,即您有有限的集合,不会经常更改)。

Static fields and methods are shared with all instances. They are for values which are specific to the class and not a specific instance. For methods, this usually are global helper methods (like Integer.parseInt()). For fields, it's usually constants (like car types, i.e. something where you have a limited set which doesn't change often).

要解决您的问题,实例化你的类的一个实例(创建一个对象),这样运行时可以为实例保留内存(否则,不同的实例会覆盖你不想要的对象)。

To solve your problem, you need to instantiate an instance (create an object) of your class so the runtime can reserve memory for the instance (otherwise, different instances would overwrite each other which you don't want).

在您的情况下,尝试此代码作为起始块:

In your case, try this code as a starting block:

public static void main (String[] args)
{
    try
    {
        MyProgram7 obj = new MyProgram7 ();
        obj.run (args);
    }
    catch (Exception e)
    {
        e.printStackTrace ();
    }
}

// instance variables here

public void run (String[] args) throws Exception
{
    // put your code here
}

新的 main ()方法创建它包含的类的实例(听起来很奇怪,但因为 main()是用类而不是实例创建的,它可以这样做),然后调用一个实例方法( run())。

The new main() method creates an instance of the class it contains (sounds strange but since main() is created with the class instead of with the instance, it can do this) and then calls an instance method (run()).

这篇关于非静态变量不能从静态上下文引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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