Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

DEPARTMENT OF

COMPUTER SCIENCE & ENGINEERING

WORKSHEET 2

Student Name: Khushi Chaudhary UID: 22BCS13783


Branch: BE-CSE Section/Group: 712-A
Semester: 3rd Date of Performance: 22 sept.
Subject Name: Java Programming Subject Code: 22CSH-201

Aim: Design a calculator software that takes all sort of inputs robust enough to
perform all possible mathematical calculations and handles in case of some trouble
some situations.

1. Source Code:

import java.util.Scanner;

public class Calculator {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

while (true) {
try {
System.out.println("Enter an expression (e.g., 2 + 3): ");
String input = scanner.nextLine();

if (input.equalsIgnoreCase("exit")) {
System.out.println("Exiting calculator.");
break;
}

double result = evaluateExpression(input);


DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

System.out.println("Result: " + result);


} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}

scanner.close();
}

public static double evaluateExpression(String input) throws Exception {


String[] tokens = input.split(" ");
if (tokens.length != 3) {
throw new IllegalArgumentException("Invalid input format. Use 'operand
operator operand'.");
}

double operand1 = Double.parseDouble(tokens[0]);


String operator = tokens[1];
double operand2 = Double.parseDouble(tokens[2]);

switch (operator) {
case "+":
return operand1 + operand2;
case "-":
return operand1 - operand2;
case "*":
return operand1 * operand2;
case "/":
if (operand2 == 0) {
throw new ArithmeticException("Division by zero is not allowed.");
}
return operand1 / operand2;
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

default:
throw new IllegalArgumentException("Unsupported operator: " +
operator);
}
}
}

2. Screenshot of Outputs:

3. Learning Outcomes
i) Learnt about scanner class.
ii) Learnt about how to handle exception.
iii) Learnt about the arithmetic calculations.

You might also like