- import java.util.Scanner;
- class Program {
- /*
- * The program reads a maths expression and computes the sum.
- * Values and operators must be separated by a space and an
- * equal = symbol used to end the expression
- *
- * e.g 5 + 5 * 2 / 4 =
- */
- public static void main(String args[]){
- System.out.println("Please enter a simple expression");
- Scanner input = new Scanner(System.in);
- double sum = 0;
- while (input.hasNext()){
- String token = input.next();
- if (token.equals( "/")){
- sum /= input.nextDouble();
- } else if (token.equals("*")){
- sum *= input.nextDouble();
- } else if (token.equals("+")){
- sum += input.nextDouble();
- } else if (token.equals("-")){
- sum -= input.nextDouble();
- } else if (token.equals("=")) {
- break;
- } else {
- sum = Double.parseDouble(token);
- }
- }
- System.out.println(sum);
- }
- }
Java - Simple Console Calculator
This code snippet takes an expression from the user and computes the sum.
No comments:
Post a Comment