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

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

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

问题

  1. public class Sum{
  2. int sum = 0;
  3. public static void sum_do(String array[]){
  4. int tmpi = 0;
  5. for (int i=0; i<array.length; ++i){
  6. tmpi = Integer.parseInt(array[i]);
  7. sum += tmpi;
  8. }
  9. }
  10. }
  1. 我想要修改 sum 变量,但是我无法做到。
  2. ./Sum.java:9: 错误: 无法从静态上下文引用非静态变量 sum
  3. sum += tmpi;
  4. ^
  5. 1 错误
  6. 我对 Java 刚入门,所以这可能是一些非常简单的东西。
英文:
  1. public class Sum{
  2. int sum = 0;
  3. public static void sum_do(String array[]){
  4. int tmpi = 0;
  5. for (int i=0; i&lt;array.length; ++i){
  6. tmpi = Integer.parseInt(array[i]);
  7. sum += tmpi;
  8. }
  9. }
  10. }

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

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

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

答案1

得分: 0

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

  1. static int sum = 0;
英文:

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

  1. 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:

确定