Implement a simple calculator java code example
Example 1: calculator program in java
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
double num1;
double num2;
double ans;
char op;
Scanner reader = new Scanner(System.in);
System.out.print("Enter two numbers: ");
num1 = reader.nextDouble();
num2 = reader.nextDouble();
System.out.print("\nEnter an operator (+, -, *, /): ");
op = reader.next().charAt(0);
switch(op) {
case '+': ans = num1 + num2;
break;
case '-': ans = num1 - num2;
break;
case '*': ans = num1 * num2;
break;
case '/': ans = num1 / num2;
break;
default: System.out.printf("Error! Enter correct operator");
return;
}
System.out.print("\nThe result is given as follows:\n");
System.out.printf(num1 + " " + op + " " + num2 + " = " + ans);
}
}
Example 2: simple calculator program in java
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Enter two numbers: ");
double first = reader.nextDouble();
double second = reader.nextDouble();
System.out.print("Enter an operator (+, -, *, /): ");
char operator = reader.next().charAt(0);
double result;
switch(operator)
{
case '+':
result = first + second;
break;
case '-':
result = first - second;
break;
case '*':
result = first * second;
break;
case '/':
result = first / second;
break;
default:
System.out.printf("Error! operator is not correct");
return;
}
System.out.printf("%.1f %c %.1f = %.1f", first, operator, second, result);
}
}