简体   繁体   English

静态方法和非静态方法Java

[英]static method and non static method Java

I know I'm doing something stupid, but I cannot figure how to fix it. 我知道我在做一些愚蠢的事情,但是我不知道该如何解决。

The issue is inside the private method removeVowels particulry when using the vowels method. 使用vowels方法时,问题出在private方法removeVowels内部。

The compiler gives 编译器给出

non-static variable vowels cannot be referenced from a static context

Here is my code: 这是我的代码:

   public class RecursionHW2 {

            String vowels;

            // Part (A) First way
            public static int upperCase(String myString){

                return upperCaseChecker(myString , 0 );
            }

            public static int upperCaseChecker(String myString, int index){

                int inc;

                //My Base Code
                if(myString.length() <= index) return 0;
                if(Character.isUpperCase(myString.charAt(index)) == true) inc= 1;
                    else inc= 0;

                return inc+upperCaseChecker(myString,index+1);
            }



            // First way of Solving part (B)
            public static int count(String str, char a)
            {
                if (str.length() == 0)
                    return 0;
                else if (str.charAt(0) == a)
                    return 1 + count(str.substring(1, str.length()), a);
                else
                    return count(str.substring(1, str.length()), a);
            }


            //Second way of solving part (B)
            public static int anotherCount(String myString, char myWord)
            {
                return anotherCount(myString, myWord, 0);
            }

            public static int anotherCount(String myString, char myWord, int index)
            {
                int inc;

                if (index >= myString.length())
                {
                    return 0;
                }

                if (myString.charAt(index) == myWord)  inc =1;
                    else
                        inc = 0;

                return inc + anotherCount(myString, myWord, index+1);
            }



            // part (C) solving
            public Boolean isSorted(int[] a, int n)
            {
            if(n == 0 || n == 1) return true;
            else
            return isSorted(a, n, 1);
            }

            private Boolean isSorted(int[] a, int n, int cur)
            {
                if(cur == n) return true;

                if(a[cur - 1] <= a[cur])
                    return isSorted(a, n, cur+1);
                else
                    return false;
            }



            //part (D) Solving
            public static String removeVowels(String myString)
            {
                return removeVowels(myString, "");
            }

            private static String removeVowels(String myString, String t)
            {
                if(myString.length() == 0) return t;

                if(vowels.contains(myString.charAt(0) + ""))
                    return removeVowels(myString.substring(1), t);
                else
                    return removeVowels(myString.substring(1), t + myString.charAt(0));
            }


        public static void main(String[] args){


            //I've wrote 2 ways to solve the Second Recursive Q2
            System.out.println("Method 1: Number of Occurence " + count("Hello  This is Mohammad Fadin",'o'));
        //  System.out.println("Method 2: Number of Occurence "+ anotherCount("Hello This is Mohammad Fadin",'o'));

            String s1 = "Hello WorlDD";
            System.out.println("Number of Upper Cases " + upperCase(s1));

            String s2 = "Hello";
            System.out.println("After Vowels Removed " + removeVowels(s2));
        }


    }

You've "infected" your code with static from your main method. 您已经通过main方法中的static “感染”了您的代码。 In your main method you should do something like this, so you don't have to make everything static : 在您的main方法中,您应该执行以下操作,因此不必使所有内容都保持static

public class RecursionHW2
{
  public static void main(String[] args)
  {
    RecursionHW2 rhw2 = new RecursionHW2();

    int count = rhw2.count("Hello world");

    // and so on
  }
}

You cannot reference an instance variable from a static context. 您不能从静态上下文引用实例变量。 You have to create an instance of RecursionHW2 first, or make the variable vowels static which makes more sense. 您必须先创建RecursionHW2的实例,或者将变量vowels设为静态 ,这才有意义。 Or you might consider to remove static modifier from removeVowels method. 或者,您可以考虑从removeVowels方法中删除静态修饰符。

Update: 更新:
However, your class looks like a bunch of utility methods, so you may want to make it non-instantiable (by adding a private constructor), make all of your methods static (because they clearly don't operate on object's state) and pass vowels as an additional parameter to removeVowels method. 但是,您的类看起来像一堆实用程序方法,因此您可能希望使其不可实例化(通过添加私有构造函数),将所有方法设为静态(因为它们显然不对对象的状态进行操作)并传递vowels作为removeVowels方法的附加参数。

The problem is exactly what the compiler tells you: you are referencing a non-static (instance) variable vowels from a static context. 问题恰恰是编译器告诉您的:您是从静态上下文引用非静态(实例) vowels Actually, almost all your methods are static which is an extremely bad design. 实际上,几乎所有方法都是静态的,这是一个非常糟糕的设计。

Make all methods which require access to instance data (here: vowels instance variable) non-static and instantiate your class in main() . 使所有需要访问实例数据的方法(此处为: vowels实例变量)都是非静态的,并在main()实例化您的类。

Change: 更改:

String vowels;

to: 至:

static String vowels;

You cannot use String vowels inside your static methods because vowels is non-static. 您不能在静态方法中使用String元音,因为元音是非静态的。 You need to add static keyword to the string, then your code will work. 您需要在字符串中添加static关键字,然后代码才能工作。

you can make the variables static or just keep everything non-static and this will get solved. 您可以将变量设为静态,也可以仅使所有内容保持非静态,这将得到解决。 The bigger question you need to ask your self is when should i use static and when not ? 您需要问自己的一个更大的问题是,什么时候应该使用static,什么时候不使用static?

change 更改

String vowels;

to

static String vowels;

All your methods are static and thus do not require an instance of your object to be present - ie you don't have to say 您的所有方法都是静态的,因此不需要存在对象的实例-即,您不必说

x = new RecursionHW2(); 
x.upperCase(..);

However if you don't make vowels static, it doesn't exist unless an object is instantiated. 但是,如果不将元音设为静态,则除非实例化对象,否则它不存在。

Static variables belong to the class, the static variables that are not belong to the class instances (objects). 静态变量属于类,而静态变量不属于类实例(对象)。

Test 测试

class Foo {

    private static String vowers;
    private String bar;

}


Foo a = new Foo ()

Are creating a new instance of class Foo, each instance has its own variable bar, but all share vowers variable because this belongs to the class. 正在创建类Foo的新实例,每个实例都有其自己的变量栏,但是所有共享vowers变量都属于该类。 Same goes with the static methods. 静态方法也是如此。

Within a static method (class method) you can not reference variables that are not static. 在静态方法(类方法)中,您不能引用非静态变量。 Why is this so? 为什么会这样呢?

imagine that from a static method you reference a variable that is not static 想象一下,从静态方法中引用的变量不是静态的

class Foo {
    private static String vowers;
    private String bar;

    public static void exampleMethod () {
       bar = "home";
    }

}

If you do this: 如果您这样做:

Foo a = new Foo () / / has a new bar
Foo b = new Foo () / / has a new bar

vowers is a single variable and belongs to the class not the instance vowers是一个变量,属于类而不是实例

When you 当你

Foo.exampleMethod()

The method does not know that variable bar used if the variable of instance a or the variable instance of b. 如果实例a的变量或b的变量实例,则该方法不知道使用变量bar Therefore you can only access static variables of the class from a static method 因此,您只能从静态方法访问该类的静态变量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM