how to write calculator program in 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: java calculator
package main;
import java.util.Scanner;
public class calculator {
public static void greetings(){
System.out.println("Hi welcome to the calculator made by Pepa pig made in java! :D");
}
public static void instruction(){
System.out.println("Hi welcome to the calculator made by Pepa pig made in java! :D");
}
public static void calculator(){
Scanner keyboardInput = new Scanner(System.in);
String calculator;
do {
System.out.print("Enter your first digit: ");
double num1 = keyboardInput.nextDouble();
System.out.print("Enter your operator: ");
String op = keyboardInput.next();
System.out.print("Enter your second digit: ");
double num2 = keyboardInput.nextDouble();
System.out.print("= ");
if (op.equals("+")){
System.out.print(num1 + num2);
System.out.println("\nYou were adding");
System.out.println("How I know that cause I have big brain and a smart programmer ;)");
}else if (op.equals("-")){
System.out.print(num1 - num2);
System.out.println("\nYou were subtracting");
System.out.println("How I know that cause I have big brain and a smart programmer ;)");
}else if (op.equals("*")){
System.out.print(num1 * num2);
System.out.println("\nYou were multiplying");
System.out.println("How I know that cause I have big brain and a smart programmer ;)");
}else if (op.equals("/")){
System.out.print(num1 / num2);
System.out.println("\nYou were dividing");
System.out.println("How I know that cause I have big brain and a smart programmer ;)");
}else if (op.equals("%")){
System.out.print(num1 % num2);
System.out.println("\nYou were remanding");
System.out.println("How I know that cause I have big brain and a smart programmer ;)");
}else{
System.out.println("Invalid operator");
}
System.out.print("Would you like to restart the calculator? (y or n): ");
calculator = keyboardInput.next();
}
while (calculator.equals("y"));
if (calculator.equals("n")){
System.out.println("Leave then kiddo ;-;");
}
}
public static void main(String[] args) {
greetings();
instruction();
calculator();
}
}