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
cse gtu, gtu study material for computer engineering students gujarat technological university oop lab manual solution

gtu oop lab manual,

oop GTU Practical,

oop Programs,

Object oriented Programming,

Gtu study material 3140705,

OOP 3140705,

oop practical list,

Java Programming,

gtu oop practical,

oop lab solution gtu

Comments

YouTube

Popular posts from this blog

GTU OOP Program - 21

GTU OS Program - 3

GTU OOP Program - 1