如何在Java中将方法级别整数和实例级别整数相加?

时间:2019-02-08 05:11:32

标签: java variables add

我得到一个错误,提示“无法从静态上下文中引用非静态变量constantInteger”

如何在不更改其整数的情况下将所有三个整数相加?

    public class VariableAdder {

      final int constantInteger = 5;
      int instanceInteger = 10;

      public static void main(String[] args) {

        int methodInteger = 20;
        int result = constantInteger + instanceInteger + methodInteger;
        System.out.println(result);

      }

    }

预期结果:添加两个实例变量和一个方法变量并打印。实际结果:错误

谢谢大家的帮助!

3 个答案:

答案 0 :(得分:3)

您不能在静态方法(在您的情况下为main())内使用实例变量(类级别,非静态,最终/非最终)

实例化VariableAdder并使用实例引用实例变量将解决您的问题。像这样:

public class VariableAdder {

    final int constantInteger = 5;
    int instanceInteger = 10;

    public static void main(String[] args) {

        VariableAdder t = new VariableAdder();

        int methodInteger = 20;
        int result = t.constantInteger + t.instanceInteger + methodInteger;
        System.out.println(result);

    }


如果您不想创建实例,请声明constantIntegerinstanceInteger为静态对象,然后直接在main()内部访问它们

答案 1 :(得分:1)

实例变量和实例常量意味着您需要一个实例才能访问它们。对于您的代码示例,这意味着创建类VariableAdder的实例。要创建实例,请调用构造函数。以下内容可在Windows 10上与JDK 11.0.2一起成功运行

public class VariableAdder {

    final int constantInteger = 5;
    int instanceInteger = 10;

    /** Constructor */
    public VariableAdder() {
    }

    public static void main(String[] args) {
        int methodInteger = 20;

        // Create an instance of class 'VariableAdder'
        VariableAdder adder = new VariableAdder();

        int result = adder.constantInteger + adder.instanceInteger + methodInteger;
        System.out.println(result);
    }
}

答案 2 :(得分:0)

这应该有效:

final static int constantInteger = 5;
static int instanceInteger = 10;

public static void main(String[] args) {

    int methodInteger = 20;
    int result = constantInteger + instanceInteger + methodInteger;
    System.out.println(result);

}

编辑:或

final static int constantInteger = 5;
static int instanceInteger = 10;

public static void main(String[] args) {

    MyClass runner = new MyClass();

    int ti=runner.instanceInteger;
    int methodInteger = 20;
    int result = constantInteger + instanceInteger + methodInteger;
    System.out.println(result);

}