Reputation: 73
I'm not sure what I did wrong here, this is my code
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();
}
}
I want to print the sum of x and y is 3
Upvotes: 1
Views: 114
Reputation: 674
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();
}
}
You can't access local variables (such as x, y of sum method) inside other method this way.
Upvotes: 0
Reputation: 236140
Try this:
System.out.println("The sum of "+ a + " and "+ b +" is "+sum(a,b));
The parameter names x
and y
are local to the method definition, in the current scope they're called a
and b
.
Alternatively, and for consistency's sake you could simply rename a
and b
to x
and y
in the printSomething()
method. The result will be exactly the same, but now the variables will have the same name.
Upvotes: 2
Reputation: 152
I am not sure about what you want to achieve, but check if this helps:
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();
}
}
Upvotes: 0