简体   繁体   English

如何在不同的类中打印方法的结果?

[英]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. 我想在Divisors类中打印位于类computeDivisor中的方法“ compute”。 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 + " , ");
        }
    }
}

} }

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. 考虑一下如果将来要计算该值并在其他计算中使用它或将其显示在STDOUT以外的其他地方时会发生什么,则必须重写该函数。 If you return the value and then do whatever you need with it on the return, you make your program more flexible. 如果返回值,然后在返回值上做任何需要的事情,则会使程序更加灵活。

Because the num integer is out of the methods scope. 因为num整数不在方法范围内。 You have to use the num variable as a parameter. 您必须使用num变量作为参数。 In other words the num variable doesn't exist in the method. 换句话说,该方法中不存在num变量。

It looks like the num variable is not even passed to the compute() method. 看起来num变量甚至没有传递给compute()方法。 In addition - we cannot see Divisors , neither computeDivisor class (which should be named ComputeDivisor ). 另外-我们看不到Divisors ,也看Divisors computeDivisor类(应该命名为ComputeDivisor )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM