PRACTICAL NO.
Question 1. Design a simple calculator using various operators and
switch case to perform various arithmetic operations in java.
Solution:
Code:
import [Link];
public class calculator
{
public static void main(String[] args) {
try {
@SuppressWarnings("resource")
Scanner reader = new Scanner([Link]);
[Link]("Enter First number : ");
double first = [Link]();
[Link]("Enter Second number :");
double second = [Link]();
[Link](" ");
[Link]("Enter an operator");
[Link]("Press 1 : Addintion");
[Link]("Press 2 : Subtraction");
[Link]("Press 3 : Multiplication");
[Link]("Press 4 : Division): ");
char operator = [Link]().charAt(0);
double result;
switch(operator)
{
case '1':
result = first + second;
break;
case '2':
result = first - second;
break;
case '3':
result = first * second;
break;
case '4':
result = first / second;
break;
// operator doesn't match any case constant (+, -, *, /)
default:
[Link]("Error! operator is not correct");
return;
}
[Link]("YOUR ANSWER IS : " + result);
[Link](" ");
[Link]("MADE BY SADIQA SADAF");
}
catch (Exception Ex)
{
throw Ex;
}
}
}
Output:
PRACTICAL NO.2
Question 2: implement a program using custom exception in java to handle user created
exception and use all the five keywords of exception handling mechanism
Solution:
Code:
public class JavaExceptionExample {
public static void main(String[] args) {
try{
//code that may raise exception
@SuppressWarnings("unused")
int data=100/0;
}
catch(ArithmeticException e)
{
[Link](e);
}
[Link](" ");
[Link]("rest of the code...");
[Link](" ");
[Link]("MADE BY SADIQA SADAF");
Output: