Java Code for Calculator. Creating a calculator in Java is a great way to practice your programming skills. Java is a versatile and powerful programming language ideal for developing desktop applications, web applications, and more. In this article, we will create a simple command line calculator by using Java programming.
Table of Contents
Java Code for Calculator
Here we are going to create a basic calculator in Java, which will be capable of performing basic mathematical tasks such as addition, subtraction, multiplication, and division. Let’s write a Java program-
import java.util.Scanner;
public class calculator {
public static void main(String[] args) throws IllegalAccessException {
Scanner sc = new Scanner(System.in);
System.out.println(" Welcome to the Java calculator");
System.out.println("\n Enter the first number ");
double n1 = sc.nextDouble();
System.out.println("Enter an operation (+, -, *, /) ");
String operator = sc.next();
System.out.println("Enter the second number ");
double n2 = sc.nextDouble();
double result;
switch (operator){
case "+":
result = n1+n2;
break;
case "-":
result = n1-n2;
break;
case "*":
result = n1*n2;
break;
case "/":
if(n2 ==0){
throw new IllegalAccessException("Division by 0 is not allowed");
}
else{
result = n1/n2;
break;
}
default:
System.out.println("Invalid operator");
return;
}
System.out.println("result = " + result);
}
}
Output
In the above Java program for the calculator, we are taking input from the user by using the Scanner class. After that, we are performing the mathematical operation selected by the user. For performing different mathmatical operations according to the user’s requirement switch
statement is used.
The calculator program in Java was introduced due to handle user input and Perform different operations according to different conditions and basics of Java.
Happy Coding & Learning
1 thought on “Java Code for Calculator”