简体   繁体   中英

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.

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. In your main method you should do something like this, so you don't have to make everything 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. Or you might consider to remove static modifier from removeVowels method.

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.

The problem is exactly what the compiler tells you: you are referencing a non-static (instance) variable vowels from a static context. 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() .

Change:

String vowels;

to:

static String vowels;

You cannot use String vowels inside your static methods because vowels is non-static. You need to add static keyword to the string, then your code will work.

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 ?

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. 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

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. Therefore you can only access static variables of the class from a static method

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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