简体   繁体   中英

How to access array or variable inside main method from other method?

So at first I made my code inside main method, and I want to divide it into several void methods to make it neat. But here is my problem, some of the variable I declared inside main method, not as instance variable. How to solve this?

public static void main(String[] args){

    String[] allcars = args;

    String[] car1 = allCars[0].split("(?!^)");
    String[] car2 = allCars[1].split("(?!^)");

    String[] tire = {car1[0], car2[0]};
    String[] color = {car1[1], car2[1]};

public static void myMethod(){
    for (int i = 0; i <= tire.length-2; i++){
        for (int j = i+1; j < tire.length; j++){
            if ((tire[i]).equals(tire[j])){
                value += 2;
            }
        }
    }
}

It gives me error tire cannot be resolved to a variable

Function parameteres are used for such things. Look an example

public static void myMethod(String[] tire);

public static void main(String[] args){

    String[] allcars = args;

    String[] car1 = allCars[0].split("(?!^)");
    String[] car2 = allCars[1].split("(?!^)");

    String[] tire = {car1[0], car2[0]};
    String[] color = {car1[1], car2[1]};

    myMethod(tire);
}

BTW, your code has syntax error - you forgot to close main function block brace.

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