如何在方法内部编辑实例变量?非静态变量sum无法在静态上下文中引用。

huangapple go评论71阅读模式
英文:

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;
        }
    }
}
我想要修改 sum 变量,但是我无法做到。

./Sum.java:9: 错误: 无法从静态上下文引用非静态变量 sum
                        sum += tmpi;
                        ^
1 错误

我对 Java 刚入门,所以这可能是一些非常简单的东西。
英文:
public class Sum{

    int sum = 0;

    public static void sum_do(String array[]){
        int tmpi = 0;
        for (int i=0; i&lt;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

答案1

得分: 0

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

static int sum = 0;
英文:

you try to reach a non-static var in a static context, try:

static int sum = 0;

huangapple
  • 本文由 发表于 2020年10月8日 01:31:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/64249334.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定