包和存取權限練習3,存取權限練習

來源:互聯網
上載者:User

包和存取權限練習3,存取權限練習

在包a中建立一個類A,在類A中有一個int add(int m)方法,用來求1+2+…+m的和。在包b中建立一個類B,在類B中有一個int cheng(int n)方法,用來求n!的結果。在包c中建立一個主類C,調用A、B中的方法輸出1+2+…+30的和,以及5!的計算結果。

包a:

 1 package a; 2  3 public class A { 4  5     public int add(int m) { 6         int sum = 0; 7         for (int i = 1; i <= m; i++) { 8             sum += i; 9         }10         return sum;11     }12     13 }

包b:

 1 package b; 2  3 public class B { 4     public int cheng(int n) { 5  6         int sum = 0;// 定義階乘的和=0 7         for (int i = 1; i <= n; i++) { 8             int factorial = 1;// 定義階乘變數 9             for (int j = 1; j <= i; j++) {10                 factorial *= j;11             }12             sum += factorial;13         }14         System.out.println("1到" + n + "的階乘和=" + sum);15         return sum;16     }17 18 }

包c:

 1 package C; 2  3 import a.*; 4 import b.*; 5  6 public class c { 7  8     public static void main(String[] args) { 9         A a = new A();10         int aa = a.add(30);11         System.out.println("sum=" + aa);12 13         B b = new B();14         int bb = b.cheng(5);15         System.out.println("sum=" + bb);16 17     }18 19 }

運行結果:

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.