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..


techstudy.org

HP 15 Core i3 7th gen Laptop(4GB, 1TB HDD, Windows 10) | Rs. 31,490

  1. import java.util.Scanner;
  2. public class Javaexcercise
  3. {
  4. public static void main(String[] args) {
  5. Scanner in = new Scanner(System.in);
  6. int p = 1;
  7.  
  8. System.out.println("Please! enter a variable 'a'.");
  9. double num1 = in.nextDouble();
  10. System.out.println("variable a = " + num1 );
  11.  
  12. System.out.println("Please! choose an operation to perform. e.g.: +, -, *, /, ^.");
  13. char o = in.next().charAt(0);
  14. System.out.println("operator = " + o);
  15.  
  16.  
  17. System.out.println("Please! enter a variable 'b'.");
  18. double num2 = in.nextDouble();
  19. System.out.println("variable b = " + num2);
  20.  
  21. System.out.print("Result : " + num1+ o + num2 + "= ");
  22.  
  23.  
  24. if(o=='+'){System.out.print(num1+num2);}
  25. else if(o=='-'){System.out.print(num1-num2);}
  26. else if(o=='*'){System.out.print(num1*num2);}
  27. else if(o=='/'){System.out.print(num1/num2);}
  28.  
  29.  
  30. else if(o=='^'){
  31. for(int i=1; i<=num2; i++){
  32. p *= num1; //We have declared int 'p' above.
  33. } System.out.print(p);
  34. }
  35. else{System.out.print("Please! enter a valid operator.");}
  36.  
  37. }
  38. }

Result

java techstudy.org

     





Related Topics




Popular Posts