Package and access permission Exercise 3. access permission exercise

Source: Internet
Author: User

Package and access permission Exercise 3. access permission exercise

Create a new class A in Package A, and there is an int add (int m) method in Class a to evaluate 1 + 2 +... + M's sum. Create a new class B in Package B, and there is an int cheng (int n) method in Class B to evaluate n! . Create A primary class c in Package C and call the methods in A and B to output 1 + 2 +... + 30 and 5! .

Package:

 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 }

Package B:

1 package B; 2 3 public class B {4 public int cheng (int n) {5 6 int sum = 0; // define the factorial sum = 0 7 for (int I = 1; I <= n; I ++) {8 int factorial = 1; // define the factorial variable 9 for (int j = 1; j <= I; j ++) {10 factorial * = j; 11} 12 sum + = factorial; 13} 14 System. out. println ("1 to" + n + "factorial and =" + sum); 15 return sum; 16} 17 18}

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

Running result:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.