简体   繁体   中英

How to edit instance variable from inside a method? non-static variable sum cannot be referenced from a static context

public class Sum{

    int sum = 0;

    public static void sum_do(String array[]){
        int tmpi = 0;
        for (int i=0; i<array.length; ++i){
            tmpi = Integer.parseInt(array[i]);
            sum += tmpi;
        }
    }
}

I'd like to modify sum variable, but I am unable to do that.

./Sum.java:9: error: non-static variable sum cannot be referenced from a static context
                        sum += tmpi;
                        ^
1 error

I'm really new to Java, so this is probably some very easy stuff

您尝试在静态上下文中访问非静态变量,请尝试:

static int sum = 0;

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