Write a Java Program to make simple Calculator using methods
import java.util.Scanner; public class CalculatorUsingMethod { public int n1,n2; public int ans = 0; CalculatorUsingMethod() { Scanner scan = new Scanner(System.in); System.out.println("Enter First Number: "); n1=scan.nextInt(); System.out.println("Enter Second Number: "); n2=scan.nextInt(); } void add() { ans=n1+n2; System.out.println(n1+" "+ "+" +" "+n2+" = "+ans); } void sub() { ans=n1-n2; System.out.println(n1+" "+ "-" +" "+n2+" = "+ans); } void mul() { ans=n1*n2; System.out.println(n1+" "+ "*" +" "+n2+" = "+ans); } void div() { ans=n1/n2; System.out.println(n1+" "+ "/" +" "+n2+" = "+ans); } public static void main(String[] args) { CalculatorUsingMethod obj = new CalculatorUsingMethod(); Scanner scan = new Scanner(System.in); System.out.println("Enter The Operator (+, -, *, /): "); char operator=scan.next().charAt(0); switch(operator) { case '+' : obj.add(); break; case '-' : obj.sub(); break; case '*' : obj.mul(); break; case '/' : obj.div(); break; default: System.out.println("You have entered wrong operator..."); } } }
Output:
Enter First Number:
30
Enter Second Number:
5
Enter The Operator (+, -, *, /):
/
30 / 5 = 6
No comments:
Post a Comment
If you have any doubts, please let me know