1

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

3
  • What does your code actually do? You appear to be using variables, x, and y, inside of the printSomething() method that are not within the scope of that method, and this should prevent your code from compiling -- is this what is wrong? Solution: use a and b there. System.out.println("The sum of "+ a + " and "+ b +" is "+sum(a,b)); Commented Feb 1, 2015 at 0:04
  • System.out.println("The sum of x and y is "+sum(a,b)); Commented Feb 1, 2015 at 0:06
  • Ok, thank you for the solution. just out of curiosity, and I'm a noob and new to this site why did i get -1 for this question? Commented Feb 1, 2015 at 0:29

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

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

You can't access local variables (such as x, y of sum method) inside other method this way.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.