Mixalis Mixalis - 4 months ago 8
Java Question

How can I invoke a method and print its result?

How can I invoke a method and print its result?

public class Test {

public static int main (String args[]){

System.out.println(total);

}

public int numbers (int a, int b){

int total;
total = a + b;
return = total;
}
}

Answer

Try this instead:

public class Test {

    public static void main (String args[]){

        System.out.println(numbers(1, 2));

    }

    public static int numbers(int a, int b){

        int total;
        total = a + b;
        return total;
    }
}

Variables are scoped to the method or class in which they are defined, therefore the 'total' variable is accessible only in the 'numbers' method

Comments