- Create three classes Add, Sub, Mul and Calculator into a package
- Use a build-in package in java to write a class which displays a message ( by using sout ) after taking input from the user
- Create a package in class with four package levels folder p1 , folder p2 , folder p3 & p5 with their respected method sum(), diff(), pro() and call all method into class Calculator.
Add.java
- package p1;
- import java.util.*;
- public class Add
- {
- int s;
- public void sum()
- {
- System.out.print("Enter the first number: ");
- Scanner scan=new Scanner(System.in);
- int x=scan.nextInt();
- System.out.print("Enter the second number: ");
- Scanner scan1=new Scanner(System.in);
- int y=scan1.nextInt();
- s=x+y;
- System.out.println("sum="+s);
- }
- }
Sub.java
- package p2;
- import java.util.*;
- public class Sub
- {
- int d;
- public void diff()
- {
- System.out.print("Enter the first number: ");
- Scanner scan=new Scanner(System.in);
- int x=scan.nextInt();
- System.out.print("Enter the second number: ");
- Scanner scan1=new Scanner(System.in);
- int y=scan1.nextInt();
- d=x-y;
- System.out.println("Difference="+d);
- }
- }
Mult.java
- package p3;
- import java.util.*;
- public class Mult
- {
- int m;
- public void pro()
- {
- System.out.print("Enter the first number: ");
- Scanner scan=new Scanner(System.in);
- int x=scan.nextInt();
- System.out.print("Enter the second number: ");
- Scanner scan1=new Scanner(System.in);
- int y=scan1.nextInt();
- m=x*y;
- System.out.println("Product="+m);
- }
- }
Now, we are going to create the main class named Calculator. In this class, we have imported all the packages that we have created above. It includes all the classes in the Calculator class.
Calculator.java
- package p5;
-
- import java.util.*;
-
- import p1.Add;
- import p2.Sub;
- import p3.Mult;
- import p4.Div;
- public class Calculator
- {
- public static void main(String args[])
- {
- System.out.print("Enter your choice: ");
- Scanner scan=new Scanner(System.in);
- int t=scan.nextInt();
- switch(t)
- {
- case 1:
- Add a=new Add();
- a.sum();
- break;
- case 2:
- Sub s=new Sub();
- s.diff();
- break;
- case 3:
- Mult m=new Mult();
- m.pro();
- break;
- case 4:
- Div d=new Div();
- d.divd();
- break;
- }
- }
- }
When we compile the above program, it creates corresponding .class files in packages named p1, p2, p3 and p5, respectively.
The .class files are generated. Now, we can run the above program. Output:
Enter your choice: 3
Enter the first number: 2
Enter the second number: 23
Product=46
..
No comments:
Post a Comment