英文:
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<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;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论