Write a Java program to create a simple calculator

Introduction

In this demo I have used NetBeans IDE 8.2 for debugging purpose. But you can use any java programming language compiler as per your availability..

import java.util.Scanner;
public class Javaexcercise
{
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int p = 1; 
 
        System.out.println("Please! enter a variable 'a'.");
        double num1 = in.nextDouble();
        System.out.println("variable a = " + num1 );
 
        System.out.println("Please! choose an operation to perform. e.g.: +, -, *, /, ^.");
        char  o = in.next().charAt(0); 
        System.out.println("operator = " + o);    
 
 
        System.out.println("Please! enter a variable 'b'.");
        double  num2 = in.nextDouble();
        System.out.println("variable b = " + num2);
 
        System.out.print("Result : " +  num1+ o + num2 +  "= ");      
 
 
        if(o=='+'){System.out.print(num1+num2);}
        else  if(o=='-'){System.out.print(num1-num2);}
        else if(o=='*'){System.out.print(num1*num2);}
        else  if(o=='/'){System.out.print(num1/num2);}
 
 
        else if(o=='^'){
           for(int i=1; i<=num2; i++){
             p *= num1; //We have declared int 'p' above.
           } System.out.print(p);
        }
        else{System.out.print("Please! enter a valid operator.");}
 
    }
}

Result

Write a Java program to create a simple calculator
Write a Java program to create a simple calculator

Leave a Comment