How to make a calculator using Java?
Calculator.java
/* Code From Learnoset - Learn Code Online Android App.*/
/*Download Learnoset App from PlayStore to learn coding*/
/*How to make a calculator using Java?*/
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
/* declare 3 int type variables num1, num2 and result.
num1 and num2 will hold the inputs from user and result will hold the calculation result
by default result have 0 value*/
int num1, num2, result = 0;
Scanner scanner = new Scanner(System.in); // Create an object of Scanner class
System.out.println("Press 1 for Addition");
System.out.println("Press 2 for Substraction");
System.out.println("Press 3 for Division");
System.out.println("Press 4 for Multiplication");
// infinity loop
while (true) {
System.out.println("What you want to perform? Choose between 1 to 4");
// calcutationType will hold the type of calculation
int calcutationType = scanner.nextInt();
System.out.println("Enter First Number");
num1 = scanner.nextInt(); // initialize num1 variable with first number entered by user.
System.out.println("Enter Second Number");
num2 = scanner.nextInt(); // initialize num2 variable with second number entered by user.
// check calcutationType and perform actions on inputs corresponsing to to calcutationType
switch (calcutationType) {
case 1:
result = num1 + num2;
System.out.println("Addition of "+num1+" and "+num2+" is = " + result);
break;
case 2:
result = num1 - num2;
System.out.println("Substraction of "+num1+" and "+num2+" is = " + result);
break;
case 3:
result = num1 / num2;
System.out.println("Division of "+num1+" and "+num2+" is = " + result);
break;
case 4:
result = num1 * num2;
System.out.println("Multiplication of "+num1+" and "+num2+" is = " + result);
break;
default:
System.out.println("You have entered wrong number. Please chooose between 1 to 4");
}
System.out.println("Do you want to continue. Press 'Y' to continue or Any other button to exit");
String exitStatus = scanner.next(); // to check wheather user want to exit or continue with new values
if (!exitStatus.equals("Y")) {
break; // this statement will exit while loop and end the program
}
}
}
}
/*----------OUTPUT----------
Press 1 for Addition
Press 2 for Substraction
Press 3 for Division
Press 4 for Multiplication
What you want to perform? Choose between 1 to 4
2
Enter First Number
6
Enter Second Number
5
Result is = 1
Do you want to continue. Press 'Y' to continue or Any other button to exit
a
*/
Projects with Source Code + Video Tutorials
You can download our Java and Android Studio Projects with Source Code and Video Tutorials.
Spin and Win App for Android (Offline Version)
Simple Music Player App (Version 2) for Android (Offline Version)
Programming Quiz App for Android (Offline Version)
If you have any Questions or Queries
You can mail us at info.learnoset@gmail.com
Follow us to learn Coding and get in touch with new Technologies.