繁体   English   中英

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

[英]Java code, passing arguments to method

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

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

尝试这个:

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

参数名称xy对于方法定义而言是局部的,在当前范围内,它们分别称为ab

另外,为了保持一致性,您可以在printSomething()方法printSomething() ab重命名为xy 结果将完全相同,但是现在变量将具有相同的名称。

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)。

我不确定要达到的目标,但是请检查是否有帮助:

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();
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM