GTU OOP Program - 13
13). Write a program for calculator to accept an expression as a string in which the operands and operator are separated by zero or more spaces. For ex: 3+4 and 3 + 4 are acceptable expressions.
- import java.util.Scanner;
- class Program_13 {
- public static void main(String[] args) {
- Scanner input = new Scanner(System.in);
- System.out.print("Enter Expression : ");
- String string = input.nextLine();
- String expr = string.replaceAll(" ", "");
- if (expr.length() < 3) {
- System.out.println("Minimum 2 operands and 1 operator required");
- System.exit(0);
- }
- int result = 0;
- int i = 0;
- while (expr.charAt(i) != '+' && expr.charAt(i) != '-' && expr.charAt(i) != '*' && expr.charAt(i) != '/') {
- i++;
- }
- switch (expr.charAt(i)) {
- case '+':
- result = Integer.parseInt(expr.substring(0, i))
- + Integer.parseInt(expr.substring(i + 1, expr.length()));
- break;
- case '-':
- result = Integer.parseInt(expr.substring(0, i))
- - Integer.parseInt(expr.substring(i + 1, expr.length()));
- break;
- case '*':
- result = Integer.parseInt(expr.substring(0, i))
- * Integer.parseInt(expr.substring(i + 1, expr.length()));
- case '/':
- result = Integer.parseInt(expr.substring(0, i))
- / Integer.parseInt(expr.substring(i + 1, expr.length()));
- break;
- }
- System.out.println(expr.substring(0, i) + ' ' + expr.charAt(i) + ' ' + expr.substring(i + 1, expr.length())
- + " = " + result);
- }
- }
Output
Comments