我不确定我在这里做错了什么, 这是我的代码
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
答案 0 :(得分:2)
试试这个:
System.out.println("The sum of "+ a + " and "+ b +" is "+sum(a,b));
参数名称x
和y
是方法定义的 local ,在当前范围内,它们被称为a
和b
或者,为了保持一致性,您只需在a
方法中将b
和x
重命名为y
和printSomething()
即可。结果将完全相同,但现在变量将具有相同的名称。
答案 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();
}
}