0% found this document useful (0 votes)
32 views3 pages

Java

Download as docx, pdf, or txt
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 3

PRACTICAL NO.

Question 1. Design a simple calculator using various operators and


switch case to perform various arithmetic operations in java.

Solution:

Code:

import java.util.Scanner;

public class calculator


{

public static void main(String[] args) {

try {
@SuppressWarnings("resource")
Scanner reader = new Scanner(System.in);
System.out.print("Enter First number : ");
double first = reader.nextDouble();
System.out.print("Enter Second number :");
double second = reader.nextDouble();
System.out.println(" ");
System.out.println("Enter an operator");
System.out.println("Press 1 : Addintion");
System.out.println("Press 2 : Subtraction");
System.out.println("Press 3 : Multiplication");
System.out.println("Press 4 : Division): ");
char operator = reader.next().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:
System.out.printf("Error! operator is not correct");
return;
}
System.out.println("YOUR ANSWER IS : " + result);
System.out.println(" ");
System.out.print("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)
{
System.out.println(e);
}
System.out.println(" ");
System.out.println("rest of the code...");
System.out.println(" ");
System.out.println("MADE BY SADIQA SADAF");

Output:

You might also like