实际和形式参数

时间:2018-04-19 01:55:57

标签: java

我用Java编写代码,它有多个方法,这些方法有多个变量。我希望其他方法使用实际和形式参数访问另一个方法的变量。我该怎么办?

我正在粘贴我面临的问题的一个例子。

Error : variable is not defined.

代码

  public class example {

    public void addition() {
        int a = 0;
        int b = 10;
        int c = a + b;
    }

    public void result() {
        System.out.println("The result for the above addition is" + c);
    }
}

2 个答案:

答案 0 :(得分:1)

好吧,你的java语法是错误的...如果你需要做一个补充,你可以这样做:

public class Addition {

    public static int addition(int a, int b)
    {
     int c= a + b;
     return c;
    }


    public static void main(String[] args) {
        int a = 1; 
        int b = 10;
        int c = addition(a,b);
        System.out.println("The result for the above addition is " + c);
    }

}

其中,add函数会添加一个+ b并将结果返回给main方法。

答案 1 :(得分:1)

  

IM收到错误的说法变量没有定义

您应该将c声明为全局变量

public class Example {

    int c;

    public void addition() {
        int a = 0;
        int b = 10;
        c = a + b;
    }

    public void result() {
        System.out.println("The result for the above addition is " + c);
    }

    public static void main(String[] args) {
        Example e = new Example();
        e.addition();
        e.result();
    }
}