Back
Java is a very high programming language. Because of the diversity java has, it's possible to build almost anything. Let’s make a simple calculator using java.
- Using the Scanner class, take two numbers
- Switch case branching is used to execute the section
- To compare the corresponding operations, use a switch case
To test the respective operations using a switch event
// Java program for simple calculator import java.io.*; // importing necessary libraries import java.lang.*; // importing necessary libraries import java.lang.Math; import java.util.Scanner; public class BasicCalculator { public static void main(String[] args) { // stores two numbers double number1, number2; // Taking input from the user Scanner sc = new Scanner(System.in); System.out.println("Please enter the numbers"); // take the inputs number1 = sc.nextDouble(); number2 = sc.nextDouble(); System.out.println("Please enter the operator (+,-,*,/)"); char op = sc.next().charAt(0); double o = 0; switch (op) { // Case to add two numbers case '+': o = num1 + num2; break; // Case to subtract two numbers case '-': o = num1 - num2; break; // Case to multiply two numbers case '*': o = num1 * num2; break; // Case to divide two numbers case '/': o = num1 / num2; break; default: System.out.println("You enter wrong input"); break; } System.out.println("The final result:"); System.out.println(); // print the final result System.out.println(num1 + " " + op + " " + num2+ " = " + o); } }
// Java program for simple calculator
import java.io.*; // importing necessary libraries
import java.lang.*; // importing necessary libraries
import java.lang.Math;
import java.util.Scanner;
public class BasicCalculator {
public static void main(String[] args)
{
// stores two numbers
double number1, number2;
// Taking input from the user
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the numbers");
// take the inputs
number1 = sc.nextDouble();
number2 = sc.nextDouble();
System.out.println("Please enter the operator (+,-,*,/)");
char op = sc.next().charAt(0);
double o = 0;
switch (op) {
// Case to add two numbers
case '+':
o = num1 + num2;
break;
// Case to subtract two numbers
case '-':
o = num1 - num2;
// Case to multiply two numbers
case '*':
o = num1 * num2;
// Case to divide two numbers
case '/':
o = num1 / num2;
default:
System.out.println("You enter wrong input");
}
System.out.println("The final result:");
System.out.println();
// print the final result
System.out.println(num1 + " " + op + " " + num2+ " = " + o);
31k questions
32.8k answers
501 comments
693 users