簡體   English   中英

我如何從另一個 class 調用該方法?

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

嗨,我正在努力解決我面臨的問題

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

}

我想做的是調用 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);
    }

}

這是我嘗試過的,但它沒有返回任何內容,即使它應該向我顯示錯誤。

如果您打算從 package 之外的其他函數訪問它們,您可能應該使用public標記聲明您的函數,即public void test() 。Java 中通常的Class 命名約定是首字母大寫,這使您的代碼更具可讀性為你和其他人。

對於你的問題,我不認為你實際上是在調用 test1 class 的test()方法。如果你希望每次都調用該方法,你可以將它放在默認構造函數中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM