Salma Salma - 3 months ago 10
Java Question

Scope of an Vector in Java

I have a vector

r1
in the main and I want to access it in the
foo
methode.

The Line
System.out.println("in : " + r1)
gives me an error :


r1 cannot be resolved to a variable


package toStack;

import java.util.Arrays;
import java.util.Vector;

public class Stack {

public static void main(String[] args) {
Vector r1 = new Vector<String>();
r1.add("O1");
r1.add("O3");

System.out.println(foo("O3"));
}

public static int foo(String o){
int num = 0;
System.out.println("in : " + r1);
if(r1.contains("O3"))
num++;
else
System.out.println(r1);
return num;
}
}


When I compile the whole code, it gives me this error :

Exception in thread "main" java.lang.Error: Unresolved compilation problems:
r1 cannot be resolved to a variable
r1 cannot be resolved
r1 cannot be resolved to a variable

at toStack.Stack.foo(Stack.java:18)
at toStack.Stack.main(Stack.java:13)


I tried to make the Vector static (which it looks like a stupid idea), and the same for public modifier.

Answer

You can either do by moving your vector initialization to class level or pass your vector to foo() as a parameter.

This would do what you wanna do;

public class Stack {
    static Vector r1 = new Vector<String>();

    public static void main(String[] args) {

        r1.add("O1");
        r1.add("O3");

        System.out.println(foo("O3"));
    }

    public static int foo(String o){
        int num = 0;
        System.out.println("in : " + r1);
        if(r1.contains("O3"))
            num++;
        else
            System.out.println(r1);
        return num;
    }
}