Anthony Kline
Anthony Kline

Reputation: 3

How to print the result of a method in a different class?

I want to print my method "compute", located in the class computeDivisor, in the Divisors class. How do I get it to who the divisors?

public static void main(String[] args) {
    Scanner s = new Scanner(System.in);
    computeDivisors cD = new computeDivisors();
    System.out.println("Enter an integer: ");
    int num = s.nextInt();
    System.out.println("The divisors of " + num + " are: ");
    cD.compute(); //Why doesn't it print?
    s.close();  
}

-

public void compute(){
    for (i = 2; i <= num / 2; i++) {
    if (num % i == 0) {
        System.out.print(i + " , ");
        }
    }
}

}

Upvotes: 0

Views: 64

Answers (3)

Jon Kiparsky
Jon Kiparsky

Reputation: 7743

You need to pass the data the the method needs as a parameter:

public void compute(int num){
    for (i = 2; i <= num / 2; i++) {
    if (num % i == 0) {
        System.out.print(i + " , ");
        }
    }

and then call the method using that parameter:

   cD.compute(num);

If I can add a design note: it would be better to return the computed value rather than printing it from the computing function. A function should do one thing, in this case that one thing is computing a value. Consider what happens if in future you want to compute this value and either use it in some other calculation or display it somewhere other than STDOUT - you'd have to rewrite the function. If you return the value and then do whatever you need with it on the return, you make your program more flexible.

Upvotes: 1

Wojtek
Wojtek

Reputation: 1308

It looks like the num variable is not even passed to the compute() method. In addition - we cannot see Divisors, neither computeDivisor class (which should be named ComputeDivisor).

Upvotes: 0

Tobias Mayr
Tobias Mayr

Reputation: 186

Because the num integer is out of the methods scope. You have to use the num variable as a parameter. In other words the num variable doesn't exist in the method.

Upvotes: 0

Related Questions