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: