Java代码,将参数传递给方法

时间:2015-02-01 00:04:00

标签: java argument-passing

我不确定我在这里做错了什么, 这是我的代码

package methods;

public class example {
    public static int sum(int x, int y){ 
        return x+y; 
    }
    public static void printSomething() {
        int a = 1; 
        int b = 2; 
        System.out.println("The sum of "+ x + " and "+ y +" is "+sum(a,b)); 
    }
    public static void main(String[] args) {
        System.out.println("Hello"); 
        printSomething();
    }
}

我想打印x和y之和为3

3 个答案:

答案 0 :(得分:2)

试试这个:

System.out.println("The sum of "+ a + " and "+ b +" is "+sum(a,b)); 

参数名称xy是方法定义的 local ,在当前范围内,它们被称为ab

或者,为了保持一致性,您只需在a方法中将bx重命名为yprintSomething()即可。结果将完全相同,但现在变量将具有相同的名称。

答案 1 :(得分:0)

package methods;

public class example {
    public static int sum(int x, int y){ 
        return x+y; 
    }
    public static void printSomething() {
        int a = 1; 
        int b = 2; 
        System.out.println("The sum of " + a + " and " + b + " is " + sum(a,b)); 
    }
    public static void main(String[] args) {
        System.out.println("Hello"); 
        printSomething();
    }
}

你不能以这种方式在其他方法中访问局部变量(例如sum方法的x,y)。

答案 2 :(得分:0)

我不确定你想要达到的目的,但检查一下是否有帮助:

package methods;

public class example {
    public static int sum(int x, int y){ 
        return x+y; 
    }
    public static void printSomething() {
        int a = 1; 
        int b = 2; 
        System.out.println("The sum of "+ a + " and "+ b +" is "+sum(a,b)); 
    }
    public static void main(String[] args) {
        System.out.println("Hello"); 
        printSomething();
    }
}