简体   繁体   English

我如何从另一个 class 调用该方法?

[英]How can i call the method from another class?

Hi i am trying to solve the problem I am facing嗨,我正在努力解决我面临的问题

public class exam {
    public static void main(String[] args) {
        test1 a = new test1();
        
       }
    int zahl(int x, int y) {
        int e;
        if(x>y) {
            e=x-y;
        }else {
            e=y-x;
        }
        if(e==0) {
            return 0;
        }
        int z=0;
        int i=1;
        while(i<=e) {
            z=z+i;
            i++;
        }
        return z;
    }

}

what I want to do is to call the zahl method to the test1 class我想做的是调用 zahl 方法到 test1 class

public class test1{
    private exam b;
    
    public void init() {
        b = new exam();
    }
    void test() {
        int result = b.zahl(2, 2);
        assertEquals(1, result);
    }

}

this is what I have tried, but it returns nothing, even though it's supposed to show me error.这是我尝试过的,但它没有返回任何内容,即使它应该向我显示错误。

You should probably be declaring your functions with the public tag ie public void test() if you intend to access them from other functions outside of that package. The usual Class naming convention in Java is with capital first letter, which makes your code more readable for you and others.如果您打算从 package 之外的其他函数访问它们,您可能应该使用public标记声明您的函数,即public void test() 。Java 中通常的Class 命名约定是首字母大写,这使您的代码更具可读性为你和其他人。

For your question, I don't think you are actually invoking the test() method of the test1 class. If you want that method to get called every time, you could place it inside the default Constructor.对于你的问题,我不认为你实际上是在调用 test1 class 的test()方法。如果你希望每次都调用该方法,你可以将它放在默认构造函数中。

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

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