Write a Java program to create a simple calculator
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:
Please! enter a variable 'a'.
50
variable a = 50
Please! choose an operation to perform. e.g.: +, -, *, /, ^.
/
operator = /
Please! enter a variable 'b'.
5
variable b = 5
Result : 50.0/5.0 = 10.0
total answers (1)
start bookmarking useful questions and collections and save it into your own study-lists, login now to start creating your own collections.
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..
Result:
Please! enter a variable 'a'.
50
variable a = 50
Please! choose an operation to perform. e.g.: +, -, *, /, ^.
/
operator = /
Please! enter a variable 'b'.
5
variable b = 5
Result : 50.0/5.0 = 10.0
need an explanation for this answer? contact us directly to get an explanation for this answer