You are on page 1of 99

SRI VENKATESWARA

INSTITUTE OF SCIENCE & TECHNOLOGY


Kolundhalur – 631 203, Thiruvallur.

PRACTICAL RECORD NOTE BOOK

DEPARTMENT OF ELECTRICAL AND ELECTRONICS ENGINEERING

CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY


SRI VENKATESWARA INSTITUTE OF SCIENCE & TECHNOLOGY
Kolundhalur – 631 203, Thiruvallur.

Register No :

Name :

Branch :

Semester :

CERTIFICATE
Certified that this is the bonafide record of work done by the above student in
the Laboratory
during the academic year

Signature of Faculty-in-Charge Signature of Head of the Dept.

Submitted for the Practical Examination held on

Internal Examiner External Examiner


INDEX

Page
S. No. Date Name of the Experiment Sign
No.

1. Electricity Bill Generation

2. Currency, Distance and Time Converter

3. Employee Payroll Processing

4. ADT Stack with Exception Handling

5. String Operations Using Arraylist

6. Implementing Abstract Classes

7. User Defined Exception Handling

8. File Operations in Java

9. Multi-Threaded Application

10. Finding the Maximum Value Using Generics

11. Calculator Using Event-Driven Programming in Java

12. Mini Project – Online Java Quiz Application


1. ELECTRICITY BILL GENERATION

Date:

AIM:

To develop a Java application for generating Electricity bill for domestic and commercial
consumers.

ALGORITHM:

1. Create a consumer class with the following members: consumer number, consumer name,
previous month reading, current month reading and type of EB connection (domestic or
commercial).
2. If the type of the EB connection is domestic, calculate the amount to be paid as follows:
• First 100 units - Rs.1 per unit
• 101-200 units - Rs.2.50 per unit
• 201 -500 units - Rs. 4 per unit
• 501 units - Rs.6 per unit

3. If the type of the EB connection is commercial, calculate the amount to be paid as follows:
• First 100 units - Rs. 2 per unit
• 101-200 units - Rs. 4.50 per unit
• 201 -500 units - Rs. 6 per unit
• 501 units - Rs. 7 per unit

4. Calculate the total amount based on the type of connection and print the result.

1
PROGRAM:

Main.java

import java.util.Scanner;

class EBBilling {

int consumer_no;

String consumer_name;

int previous_month_reading;

int current_month_reading;

int units_consumed;

int connection_type;

double amount;

public void getDetails() {

Scanner inputs = new Scanner(System.in);

System.out.println("Enter Your Consumer Name : ");

consumer_name = inputs.next();

System.out.println("Enter Your Consumer Number : ");

consumer_no = inputs.nextInt();

System.out.println("Enter Previous Month Reading : ");

previous_month_reading = inputs.nextInt();

System.out.println("Enter Current Month Reading : ");

current_month_reading = inputs.nextInt();

System.out.println("Enter Your Connection Type (1 - Domestic, 2 - Commercial) : ");

connection_type = inputs.nextInt();

inputs.close();

public void calculateBill() {

double sum = 0;

units_consumed = current_month_reading - previous_month_reading;

2
if (connection_type == 1) {

for (int i = 1; i <= units_consumed; i++) {

if (i <= 100)

sum = sum + 1;

else if (i > 100 && i <= 200)

sum = sum + 2.5;

else if (i > 200 && i <= 500)

sum = sum + 4;

else

sum = sum + 6;

} else if (connection_type == 2) {

for (int i = 1; i <= units_consumed; i++) {

if (i <= 100)

sum = sum + 2;

else if (i > 100 && i <= 200)

sum = sum + 4.5;

else if (i > 200 && i <= 500)

sum = sum + 6;

else

sum = sum + 7;

else {

System.out.println("Please Enter a Valid Connection Type!\n");

System.exit(0);

amount = sum;

3
public void domesticTariff() {

System.out.println("Domestic Connection Tariff");

System.out.println("**************************");

System.out.println("First 100 units - Rs. 1.00 per unit");

System.out.println("101-200 units - Rs. 2.50 per unit");

System.out.println("201 -500 units - Rs. 4.00 per unit");

System.out.println("> 501 units - Rs. 6.00 per unit");

public void commercialTariff() {

System.out.println("Commercial Connection Tariff");

System.out.println("****************************");

System.out.println("First 100 units - Rs. 2.00 per unit");

System.out.println("101-200 units - Rs. 4.50 per unit");

System.out.println("201 -500 units - Rs. 6.00 per unit");

System.out.println("> 501 units - Rs. 7.00 per unit");

public void displayBill() {

calculateBill();

System.out.println("The Electricity Bill Details");

System.out.println("****************************");

System.out.println("Consumer Name : " + consumer_name);

System.out.println("Consumer Number : " + consumer_no);

System.out.println("Consumer Units Consumed : " + units_consumed);

if (connection_type == 1) {

System.out.println("Connection Type is : Domestic");

domesticTariff();

} else {

System.out.println("Connection Type is : Commercial");

commercialTariff();

4
}

System.out.println("\nAmount Payable is : " + amount);

public class Main {

public static void main(String[] args) {

EBBilling consumer = new EBBilling();

consumer.getDetails();

consumer.displayBill();

5
OUTPUT:

RESULT:

The Java program to generate the electricity bill for consumers was successfully executed.

6
2. CURRENCY, DISTANCE AND TIME CONVERTER

Date:

AIM:

To develop a Java application to implement currency converter, distance converter and time
converter using packages.

ALGORITHM:

1. Create three packages to represent the given converters ( currency, distance and time ).
2. Depending on the choice selected, implement the conversion routines by using
appropriate formulae.
3. Perform conversion for the following:
• Currency converter – Dollar, Euro and Yen to INR & vice versa
• Distance converter – Meter , Miles to KM & vice versa
• Time converter – Hours to minutes, seconds & vice versa
4. Print the result of the conversion as the output.

7
PROGRAM:

Currency.java

package com.ex2.converter;

import java.util.Scanner;

public class Currency {

public static double DollarToInr(double dollar) {

return dollar * 68.59;

public static double InrToDollar(double inr) {

return inr * 0.015;

public static double EuroToInr(double euro) {

return euro * 80.34;

public static double InrToEuro(double inr) {

return inr * 0.012;

public static double YenToInr(double yen) {

return yen * 0.61;

public static double InrToYen(double inr) {

return inr * 1.64;

8
public static void userChoice() {

Scanner inputs = new Scanner(System.in);

int choice = 0;

double money = 0;

System.out.println("CURRENCY CONVERTER");

System.out.println("******************");

System.out.println("1. Dollars to Indian Rupee");

System.out.println("2. Indian Rupee to Dollars");

System.out.println("3. Euros to Indian Rupee");

System.out.println("4. Indian Rupee to Euros");

System.out.println("5. Yen to Indian Rupee");

System.out.println("6. Indian Rupee to Yen");

System.out.println("\nEnter your Choice : ");

choice = inputs.nextInt();

switch (choice) {

case 1:

System.out.println("Enter the Dollar Amount");

money = inputs.nextDouble();

System.out.println(money + " Dollar is equal to " + DollarToInr(money) + " INR");

break;

case 2:

System.out.println("Enter the Indian Rupee Amount");

money = inputs.nextDouble();

System.out.println(money + " INR is equal to " + InrToDollar(money) + " Dollars");

break;

9
case 3:

System.out.println("Enter the Euro Amount");

money = inputs.nextDouble();

System.out.println(money + " Euro is equal to " + EuroToInr(money) + " INR");

break;

case 4:

System.out.println("Enter the Indian Rupee Amount");

money = inputs.nextDouble();

System.out.println(money + " INR is equal to " + InrToEuro(money) + " Euros");

break;

case 5:

System.out.println("Enter the Yen Amount");

money = inputs.nextDouble();

System.out.println(money + " Yen is equal to " + YenToInr(money) + " INR");

break;

case 6:

System.out.println("Enter the Indian Rupee Amount");

money = inputs.nextDouble();

System.out.println(money + " INR is equal to " + InrToYen(money) + " Yen");

break;

default:

System.out.println("\nInvalid Choice");

break;

inputs.close();

10
Distance.java

package com.ex2.converter;

import java.util.Scanner;

public class Distance {

public static double KMToMeter(double kilometer) {

return kilometer * 1000;

public static double MeterToKM(double meter) {

return meter / 1000;

public static double KMToMiles(double kilometer) {

return kilometer / 1.609344;

public static double MilesToKM(double miles) {

return miles * 1.609344;

public static void userChoice(){

Scanner inputs = new Scanner(System.in);

int choice = 0;

double distance = 0;

System.out.println("DISTANCE CONVERTER");

System.out.println("******************");

System.out.println("1. Kilometer to Meter");

System.out.println("2. Meter to Kilometer");

11
System.out.println("3. Kilometer to Miles");

System.out.println("4. Miles to Kilometer");

System.out.println("\nEnter your Choice : ");

choice = inputs.nextInt();

switch(choice){

case 1:

System.out.println("Enter the Distance in Kilometers : ");

distance = inputs.nextDouble();

System.out.println(distance+" KILOMETER is equal to "+KMToMeter(distance)+"

Meters");

break;

case 2:

System.out.println("Enter the Distance in Meters : ");

distance = inputs.nextDouble();

System.out.println(distance+" Meters is equal to "+MeterToKM(distance)+"

Kilometers");

break;

case 3:

System.out.println("Enter the Distance in Kilometers : ");

distance = inputs.nextDouble();

System.out.println(distance+" KILOMETER is equal to "+(KMToMiles(distance))+"

Miles");

break;

case 4:

System.out.println("Enter the Distance in Miles : ");

12
distance = inputs.nextDouble();

System.out.println(distance+" MILES is equal to "+MilesToKM(distance)+"

Kilometers");

break;

default:

System.out.println("\nInvalid Choice");

break;

inputs.close();

Time.java

package com.ex2.converter;

import java.util.Scanner;

public class Time {

public static double HoursToMins(double hours) {

return hours * 60;

public static double MinsToHours(double minutes) {

return minutes / 60;

public static double HoursToSecs(double hours) {

return hours * 60 * 60;

13
public static double SecsToHours(double seconds) {

return seconds / 60 / 60;

public static void userChoice(){

Scanner inputs = new Scanner(System.in);

int choice = 0;

double time = 0;

System.out.println("TIME CONVERTER");

System.out.println("**************");

System.out.println("1. Hours to Minutes");

System.out.println("2. Minutes to Hours");

System.out.println("3. Hours to Seconds");

System.out.println("4. Seconds to Hours");

System.out.println("\nEnter your Choice : ");

choice = inputs.nextInt();

switch(choice){

case 1:

System.out.println("Enter Hours");

time = inputs.nextDouble();

System.out.println(time+ " Hours equals " +Time.HoursToMins(time) +" Minutes");

break;

case 2:

System.out.println("Enter Minutes");

time = inputs.nextDouble();

System.out.println(time+ " Minutes equals " +Time.MinsToHours(time) +" Hours");

break;

14
case 3:

System.out.println("Enter Hours");

time = inputs.nextDouble();

System.out.println(time+ " Hours equals " +Time.HoursToSecs(time) +" Seconds");

break;

case 4:

System.out.println("Enter Seconds");

time = inputs.nextDouble();

System.out.println(time+ " Seconds equals " +Time.SecsToHours(time)+ " Hours");

break;

default:

System.out.println("Please choose valid option");

break;

inputs.close();

Main.java

package com.ex2;

import java.util.Scanner;

import com.ex2.converter.*;

public class Main {

public static void main(String[] args) {

Scanner inputs = new Scanner(System.in);

int choice = 0;

15
System.out.println("CONVERTER");

System.out.println("*********");

System.out.println("1. Currency Converter");

System.out.println("2. Distance Converter");

System.out.println("3. Time Converter");

System.out.println("\nPlease Enter Your Choice : ");

choice = inputs.nextInt();

switch(choice){

case 1:

Currency.userChoice();

break;

case 2:

Distance.userChoice();

break;

case 3:

Time.userChoice();

break;

default:

System.out.println("Invalid Option");

break;

inputs.close();

16
OUTPUT:

17
RESULT:
The Java program to implement the currency, distance and time converter were successfully
implemented.

18
3. EMPLOYEE PAYROLL PROCESSING

Date:

AIM:

To write a Java program to create pay slips for employees by utilizing the concept of
inheritance.

ALGORITHM:

1. Create an Employee class with the following members : employee name, employee ID,

address, mail id and mobile number.

2. Inherit the classes - Programmer, Assistant Professor, Associate Professor and Professor

from the Employee class.

3. Add Basic Pay (BP) as the member of all the inherited classes with 97% of BP as DA, 10%

of BP as HRA, 12% of BP as PF, 0.1% of BP for staff club fund.

4. Generate pay slips for the employees with their gross and net salary.

19
PROGRAM:

Employee.java

package workforce;

import java.util.Scanner;

class Employee {

String emp_name;

String emp_id;

String address;

String mail_id;

String mobile_no;

int basic_pay, daily_pay, current_basic_pay;

int da, hra, pf, staff_club_fund;

int net_pay, gross_pay;

int work_days_in_current_month;

int days_worked;

Scanner input;

Employee() {

input = new Scanner(System.in);

getUserDetails();

System.out.println("\nEnter the number of working days in the Current Month : ");

work_days_in_current_month = input.nextInt();

public void generatePaySlip() {

da = (current_basic_pay / 100) * 97;

hra = (current_basic_pay / 100) * 10;

pf = (current_basic_pay / 100) * 12;

20
staff_club_fund = (int) ((current_basic_pay / 100) * 0.1);

gross_pay = current_basic_pay + da + hra + pf + staff_club_fund;

int deductions = pf + staff_club_fund;

net_pay = gross_pay - deductions;

public void displayPaySlip() {

System.out.println("Employee Name : " + emp_name);

System.out.println("Employee ID : " + emp_id);

System.out.println("Address : " + address);

System.out.println("E-Mail : " + mail_id);

System.out.println("Mobile Number : " + mobile_no);

System.out.println("\n");

System.out.println("BASIC Pay : Rs." + current_basic_pay);

System.out.println("DA : Rs." + da);

System.out.println("HRA : Rs." + hra);

System.out.println("PF : Rs." + pf);

System.out.println("Staff Club Fund : Rs." + staff_club_fund);

System.out.println("\n");

System.out.println("GROSS Pay : Rs." + gross_pay);

System.out.println("NET Pay : Rs." + net_pay);

public void getUserDetails() {

System.out.println("Name : ");

emp_name = input.next();

System.out.println("ID : ");

emp_id = input.next();

System.out.println("Address : ");

21
address = input.next();

System.out.println("EMail : ");

mail_id = input.next();

System.out.println("Mobile No :");

mobile_no = input.next();

public void computeBasicPay(String empType) {

daily_pay = basic_pay / work_days_in_current_month;

System.out.println("\nBasic Pay of " + empType + " is " + basic_pay + " for " +

work_days_in_current_month + " working days");

System.out.println("Current month the " + empType + " gets Rs. " + daily_pay + " as basic

pay / day");

System.out.println("\n\nEnter the number of days worked by the " + empType + " : ");

days_worked = input.nextInt();

if (days_worked <= work_days_in_current_month) {

current_basic_pay = daily_pay * days_worked;

System.out.println("\n\n");

System.out.println("Employee Pay Slip");

System.out.println("*****************");

generatePaySlip();

} else {

System.out.println("Invalid number of days worked");

22
Programmer.java

package workforce;

public class Programmer extends Employee {

public Programmer() {

super();

computeProgrammerPay();

public void computeProgrammerPay() {

System.out.println("Enter Basic pay of the Programmer : ");

basic_pay = input.nextInt();

computeBasicPay("Programmer");

generatePaySlip();

displayPaySlip();

AsstProfessor.java

package workforce;

public class AsstProfessor extends Employee {

public AsstProfessor() {

super();

computeAssistantProfessorPay();

public void computeAssistantProfessorPay() {

System.out.println("Enter Basic pay of the Assistant Professor : ");

basic_pay = input.nextInt();

computeBasicPay("Assistant Professor");

generatePaySlip();

displayPaySlip();

23
AssocProfessor.java

package workforce;

public class AssocProfessor extends Employee {

public AssocProfessor() {

super();

computeAssociateProfessorPay();

public void computeAssociateProfessorPay() {

System.out.println("Enter Basic pay of the Associate Professor : ");

basic_pay = input.nextInt();

computeBasicPay("Associate Professor");

generatePaySlip();

displayPaySlip();

Professor.java

package workforce;

public class Professor extends Employee {

public Professor() {

super();

computeProfessorPay();

public void computeProfessorPay() {

System.out.println("Enter Basic pay of the Professor : ");

basic_pay = input.nextInt();

computeBasicPay("Professor");

generatePaySlip();

displayPaySlip();

24
Main.java

import java.util.Scanner;

import workforce.*;

public class Main {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

int choice;

System.out.println("\nEmployee Category");

System.out.println("*******************");

System.out.println("1. Programmer");

System.out.println("2. Assistant Professor");

System.out.println("3. Associate Professor");

System.out.println("4. Professor");

System.out.println("5. Exit");

System.out.println("Enter Your Choice : ");

choice = input.nextInt();

switch (choice) {

case 1:

System.out.println("Programmer Details");

System.out.println("******************");

new Programmer();

break;

case 2:

System.out.println("Assistant Professor Details");

System.out.println("***************************");

new AsstProfessor();

break;

25
case 3:

System.out.println("Associate Professor Details");

System.out.println("***************************");

new AssocProfessor();

break;

case 4:

System.out.println("Professor Details");

System.out.println("*****************");

new Professor();

default:

System.exit(0);

break;

input.close();

26
OUTPUT:

27
RESULT:
The Java program to implement pay slip generation for employees through inheritance was
successfully executed.

28
4. ADT STACK WITH EXCEPTION HANDLING

Date:

AIM:

To design a Java interface for ADT Stack array.

ALGORITHM:

1. Create an array to store the elements of the stack.

2. Get the option from the user for performing array operations like : push, pop and display.

3. If the user option is push then check if the stack is full. If not enter the element on top of

the existing elements in the stack.

4. If the user option is pop then check if the stack is empty. If not, remove the element

present on top of the stack.

5. If the user option is display, then display all the elements present on the stack.

29
PROGRAM:

Operations.java

package stackfiles;

public interface Operations {

void push(int number);

void pop();

void display();

Stack.java

package stackfiles;

public class Stack implements Operations {

int items[];

int capacity;

int position = 0;

public Stack(int capacity) {

this.capacity = capacity;

items = new int[capacity];

initStack();

public void initStack() {

for (int i = 0; i < capacity; i++)

items[i] = -1;

public void push(int number) {

try {

items[position] = number;

position++;

30
System.out.println("\nThe element " + number + " is at position " + position);

display();

catch (ArrayIndexOutOfBoundsException e) {

System.out.println("\nStack capacity FULL.");

public void pop() {

int pop_element;

try {

pop_element = items[position - 1];

items[position - 1] = -1;

position--;

System.out.println("\nPoped element is : " + pop_element);

display();

} catch (ArrayIndexOutOfBoundsException e) {

System.out.println("\nStack is EMPTY");

public void display() {

System.out.println("\n");

System.out.println("STACK");

System.out.println("*****");

for (int i = capacity - 1; i >= 0; i--)

if (items[i] != -1)

System.out.println(items[i]);

System.out.println("*****");

31
Main.java

import java.util.Scanner;

import stackfiles.*;

public class Main {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

System.out.print("Enter the Stack Size :");

int limit = input.nextInt();

Stack mystack = new Stack(limit);

int choice=0;

while (choice <= 4) {

System.out.println("\n1.PUSH");

System.out.println("2.POP");

System.out.println("3.DISPLAY");

System.out.println("4.EXIT");

System.out.println("\nEnter Stack Operation : ");

choice = input.nextInt();

switch (choice) {

case 1:

System.out.println("Enter the Element to Push : ");

mystack.push(input.nextInt());

break;

case 2:

mystack.pop();

break;

case 3:

mystack.display();

break;

32
default:

System.exit(0);

break;

input.close();

33
OUTPUT:

34
RESULT:
The Java program to implement the ADT Stack using arrays was executed successfully.

35
5. STRING OPERATIONS USING ARRAYLIST

Date:

AIM:

To write a Java program to perform string operations using ArrayList.

ALGORITHM:

1. Create an array list to hold the string items entered by the user.

2. Based on the user choice perform the following operations:

a. Append a string

b. Insert a string at position

c. Search a string

d. Display strings beginning with an alphabet

3. If the option is to append a string, place the string beneath the string already present in

the array list.

4. If the option is to insert a string, then get the position and string from the user and place

the entered string at the position defined by the user.

5. If the option is to search the string, output the result whether the string is present in the

array list or not.

6. If the option is to display strings beginning with the alphabet, get the user option for the

beginning alphabet and display all the strings present within the array list starting with

the entered alphabet.

36
PROGRAM:

StringOperations.java

import java.util.ArrayList;

public class StringOperations {

ArrayList<String> wordList;

public StringOperations() {

wordList = new ArrayList<String>();

public void addString(String aString) {

wordList.add(aString);

displayList();

public void insertStringAt(int position, String aString) {

int list_size = wordList.size();

int cur_pos = 0;

ArrayList<String> templist = new ArrayList<String>();

if (position > list_size)

System.out.println("Position NOT available in the list");

else {

for (String elememt : wordList) {

if (cur_pos == position - 1)

templist.add(aString);

templist.add(elememt);

cur_pos++;

37
}

wordList = templist;

displayList();

public void displayList() {

System.out.println("\n");

System.out.println("Contents of List");

System.out.println("****************");

int i = 0;

for (String element : wordList) {

System.out.println((i + 1) + "." + element);

i++;

System.out.println("****************");

System.out.println("\n");

public void searchString(String aString) {

int cur_pos = 0;

int foundAt = -1;

for (String element : wordList) {

if (element.equalsIgnoreCase(aString)) {

foundAt = cur_pos;

break;

} else

cur_pos++;

38
if (foundAt >= 0) {

System.out.println("String " + aString + " found at position " + (cur_pos + 1));

System.out.println("\n");

} else

System.out.println("Searched String NOT Found");

public void displayStringsBeginWith(String aLetter) {

System.out.println("The String Beginning with Letter [" + aLetter + "]\n");

for (String element : wordList) {

String firstLetter = String.valueOf(element.charAt(0));

if (aLetter.equals(firstLetter))

System.out.println(element);

System.out.println("\n");

Main.java

import java.util.Scanner;

public class Main {

public static void main(String[] args) {

StringOperations myStrings = new StringOperations();

Scanner inputs = new Scanner(System.in);

String stringInput = null;

int choice = 0;

int position = 0;

while (choice != 6) {

System.out.println("List Operations");

System.out.println("***************");

39
System.out.println("1. Append a String");

System.out.println("2. Insert String at Position");

System.out.println("3. Search a String");

System.out.println("4. Display String Beginning with a Letter");

System.out.println("5.Exit");

System.out.println("Enter Your Option : ");

choice = inputs.nextInt();

switch (choice) {

case 1:

System.out.println("Enter the String: ");

myStrings.addString(inputs.next());

break;

case 2:

System.out.println("Enter a String: ");

stringInput = inputs.next();

System.out.println("Enter the Position to Insert: ");

position = inputs.nextInt();

myStrings.insertStringAt(position, stringInput);

break;

case 3:

System.out.println("Enter a String to Be Searched: ");

stringInput = inputs.next();

myStrings.searchString(stringInput);

break;

case 4:

System.out.println("Enter the Begining Letter to Search:");

myStrings.displayStringsBeginWith(inputs.next());

break;

40
case 5:

default:

inputs.close();

System.exit(0);

break;

41
OUTPUT:

42
43
RESULT:
The Java program to perform string operations using ArrayList was successfully performed.

44
6. IMPLEMENTING ABSTRACT CLASSES

Date:

AIM:

To write a Java program to implement an Abstract Class and to extend it to create concrete
classes.

ALGORITHM:

1. Create an abstract class which contains the basic dimensional values of the shapes like

length, height and area

2. Extend the abstract shape class to create three concrete classes namely – Rectangle,

Triangle and Circle

3. If the choice entered is rectangle, then compute the area of the rectangle based upon the

formula and display the area of the rectangle as the output.

4. If the choice entered is triangle, then compute the area of the triangle based upon the

formula and display the area of the triangle as the output.

5. If the choice entered is circle, then compute the area of the circle based upon the formula

and display the area of the circle as the output.

45
PROGRAM:

Shape.java

package shapes;

public abstract class Shape {

double length = 0.0;

double height = 0.0;

double area = 0.0;

public abstract void printArea();

Rectangle.java

package shapes;

import java.util.Scanner;

public class Rectangle extends Shape {

Scanner inputs = new Scanner(System.in);

public void printArea() {

System.out.println("\n");

System.out.println("Enter Length of the Rectangle : ");

length = inputs.nextDouble();

System.out.println("Enter Breadth of the Rectangle : ");

height = inputs.nextDouble();

area = length * height;

System.out.println("Area of the Rectangle is : " + area);

46
Triangle.java

package shapes;

import java.util.Scanner;

public class Triangle extends Shape {

Scanner inputs = new Scanner(System.in);

public void printArea() {

System.out.println("\n");

System.out.println("Enter Length of the Triangle : ");

length = inputs.nextDouble();

System.out.println("Enter Height of the Triangle : ");

height = inputs.nextDouble();

area = 0.5 * length * height;

System.out.println("Area of the Triangle is : " + area);

Circle.java

package shapes;

import java.util.Scanner;

public class Circle extends Shape {

Scanner inputs = new Scanner(System.in);

public void printArea() {

System.out.println("\n");

System.out.println("Enter Radius of Circle : ");

47
length = inputs.nextDouble();

area = Math.PI * length * length;

System.out.println("Area of the Circle is : " + area);

Main.java

import shapes.*;

import java.util.Scanner;

public class Main {

public static void main(String[] args) {

Scanner inputs = new Scanner(System.in);

int choice = 0;

do {

System.out.println("\n");

System.out.println("Area of Shapes");

System.out.println("**************");

System.out.println("1. Rectangle");

System.out.println("2. Triangle");

System.out.println("3. Circle");

System.out.println("4. Exit");

System.out.println("Enter Your Choice : ");

choice = inputs.nextInt();

48
switch (choice) {

case 1:

Shape rectangle = new Rectangle();

rectangle.printArea();

break;

case 2:

Shape triangle = new Triangle();

triangle.printArea();

break;

case 3:

Shape circle = new Circle();

circle.printArea();

break;

case 4:

inputs.close();

System.exit(0);

default:

System.out.println("Invalid choice");

break;

} while (choice < 4);

49
OUTPUT:

50
RESULT:
The Java program to implement an Abstract Class for finding the area of shapes was
implemented successfully.

51
7. USER DEFINED EXCEPTION HANDLING

Date:

AIM:

To implement user defined exception handling mechanism in Java.

ALGORITHM:

1. Enter the student name and the marked obtained as inputs.

2. Validate the name of the student using Regular Expressions. If the validation fails then

print the appropriate message to enter a valid name.

3. Validate the marks obtained by the student. If the mark is below 0 or above 100, then

print message to enter an appropriate mark within range.

4. If validation passes, print given messages for the student based on the range of marks

obtained.

52
PROGRAM:

StudentMarks.java

package exceptions;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

public class StudentMarks {

public String name;

public int marks;

public StudentMarks(String name, int marks) {

this.name = name;

this.marks = marks;

public static boolean isBetween(int x, int lower, int upper) {

return lower <= x && x <= upper;

public void nameValidation() {

try {

CharSequence inputStr = name;

// for checking a string with only letters and spaces

Pattern pattern = Pattern.compile(new String("^[a-zA-Z.\\s]*$"));

Matcher matcher = pattern.matcher(inputStr);

53
if (matcher.matches())

System.out.println("Hello, " + name);

else

throw new ValidateName();

} catch (ValidateName e) {

public void marksValidation() {

try {

if (isBetween(marks, 0, 49)) {

System.out.println("Need to Improve Your Scores");

} else if (isBetween(marks, 50, 70)) {

System.out.println("Put Even More Effort in Your Studies");

} else if (isBetween(marks, 71, 90)) {

System.out.println("Keep Up the Good Work");

} else if (isBetween(marks, 91, 100)) {

System.out.println("Excellent Job !!");

} else

throw new ValidateMarks();

} catch (ValidateMarks e) {

54
ValidateMarks.java

package exceptions;

@SuppressWarnings("serial")

public class ValidateMarks extends Exception {

public ValidateMarks() {

System.out.println("Enter a Mark in the Range 0 to 100");

ValidateName.java

package exceptions;

@SuppressWarnings("serial")

public class ValidateName extends Exception {

public ValidateName() {

System.out.println("Enter a Valid Name");

Main.java

import exceptions.*;

import java.util.Scanner;

public class Main {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

String name;

int marks;

System.out.println("Enter Your Name :");

name = input.nextLine();

System.out.println("Enter Your Marks :");

marks = input.nextInt();

55
StudentMarks aStudent = new StudentMarks(name, marks);

aStudent.nameValidation();

aStudent.marksValidation();

input.close();

56
OUTPUT:

57
RESULT:

The Java program for user defined exception handling to validate name and marks obtained
was successfully implemented.

58
8. FILE OPERATIONS IN JAVA

Date:

AIM:

To write a Java program to implement basic file handling features.

ALGORITHM:

1. Get the fully qualified path of the file from the user as input.

2. Based on the path, check if the given file is present. If not display message stating the

file does not exist.

3. If the file is present then display the following properties of the file:

a. The location of the file

b. The attribute of the file – whether it is readable, writable or both

c. The type or the extension of the file

d. The size of the file in bytes

59
PROGRAM:

UserFileHandler.java

import java.io.File;

public class UserFileHandler {

File myFile;

boolean readable = false;

boolean writeable = false;

boolean exists = false;

int length = 0;

public UserFileHandler(String path) {

myFile = new File(path);

exists = myFile.exists();

readable = myFile.canRead();

writeable = myFile.canWrite();

length = (int) myFile.length();

public String getFileExtension(File inpFile) {

String fileName = inpFile.getName();

if (fileName.lastIndexOf(".") != -1 && fileName.lastIndexOf(".") != 0)

return fileName.substring(fileName.lastIndexOf(".") + 1);

else

return "";

public void fileDetails() {

if (exists) {

60
System.out.println("The File \"" + myFile.getName() + "\" Exists at Location - " +

myFile.getParent());

if (readable && writeable)

System.out.println("The File is Readable and Writeable");

else if (readable)

System.out.println("The File is Only Readable");

else if (writeable)

System.out.println("File is Only Writeable");

System.out.println("The File is of Type : " + getFileExtension(myFile));

System.out.println("The Total Length of the File is : " + this.length + " bytes");

} else

System.out.println("The File DOES NOT exists ");

Main.java

import java.util.Scanner;

public class Main {

public static void main(String[] args) {

String file_path = null;

Scanner input = new Scanner(System.in);

System.out.println("Enter the Path of the File : ");

file_path = input.next();

new UserFileHandler(file_path).fileDetails();

input.close();

61
OUTPUT:

RESULT:

The Java program to implement basic file handling features to check the location, attributes,
file type & size of a given file was successfully implemented.

62
9. MULTI - THREADED APPLICATION

Date:

AIM:

To write a Java program to implement a multi – threaded application.

ALGORITHM:

1. Create a java program that spawns three threads.

2. The first thread generates a random number within the range 0 to 1000, and prints it as

the output.

3. The second thread checks if the random number is even or not. If it is even, it calculates

the square of the said number and displays it as the output.

4. The third thread checks if the random number is odd or not. If odd, it calculates the cube

of the said number and displays it as the output.

63
PROGRAM:

RandomIntThread.java

package threads;

import java.util.Random;

public class RandomIntThread extends Thread {

Random number = new Random();

int value;

public void run() {

while (true) {

try {

sleep(1000);

} catch (InterruptedException e) {

value = number.nextInt(1000);

System.out.println("First Thread - Random Number : " + value);

if (value % 2 == 0)

new SquareThread(value).start();

else

new CubeThread(value).start();

SquareThread.java

package threads;

public class SquareThread extends Thread{

int number;

int square;

public SquareThread(int number) {

64
this.number = number;

public void run(){

square = number * number;

System.out.println("Second Thread : EVEN Number - Square of "+number+" is "+square);

CubeThread.java

package threads;

public class CubeThread extends Thread{

int number;

int cube;

public CubeThread(int number) {

this.number = number;

public void run(){

cube = number * number * number;

System.out.println("Third Thread : ODD Number - Cube of "+number+" is "+cube);

Main.java

import threads.*;

public class Main {

public static void main(String[] args) {

new RandomIntThread().start();

65
OUTPUT:

RESULT:

A Java program to implement a multi – threaded application which generates a random


number and squares it if it is even and cubes it if odd, was implemented successfully.

66
10. FINDING THE MAXIMUM VALUE USING GENERICS

Date:

AIM:

To write a java program to find the maximum value from the given array of elements by
using a generic function.

ALGORITHM:

1. Create a generic array that can hold different types of elements of similar types.

2. Populate the array with numbers and call the function to find the maximum element

present in the array.

3. Print the number as the maximum number in the array.

4. Similarly populate the generic array with strings and call the same function to find the

maximum element present in the array

5. Print the element in the array with the largest value.

67
PROGRAM:

Maximum.java

class Maximum {

public <T extends Comparable<T>> void maxFinder (T[] array){

T max = array[0];

System.out.println("The Values Entered Are : ");

for(T element: array){

System.out.print(element +" ");

if(element.compareTo(max) > 0)

max = element;

System.out.println("\nThe Maximum Value is : "+max);

Main.java

public class Main {

public static void main(String[] args) {

Maximum max = new Maximum();

Integer[] numbers = {12,433,50,100,78};

String[] strings = {"A","App","Apple"};

max.maxFinder(numbers);

System.out.println("\n");

max.maxFinder(strings);

68
OUTPUT:

RESULT:

The Java program to find the maximum value from the given array of elements by using a
generic function was successfully implemented.

69
11. CALCULATOR USING EVENT-DRIVEN PROGRAMMING IN JAVA

Date:

AIM:

To create a calculator in Java using event driven programming for implementing standard /
scientific calculations

ALGORITHM:

1. Create a AWT application to produce a frame for displaying a graphics based calculator.

2. Populate the container with digits from 0 to 9 and with symbols like +, -, *, / , = and .

3. Based on the mouse input from the user, display the appropriate actions performed by

displaying it on the calculator output text box.

4. Perform the calculations and display the output when the ‘=’ button is clicked

5. The SCI/STD is used to toggle the calculator between the Scientific and Standard modes.

6. When the Scientific mode is enabled, display buttons like – sin, cos, tan and log, for

performing scientific calculations.

7. Similarly perform the clicked operation and display the result on the calculator window.

70
PROGRAM:

Main.java

import java.awt.*;

import java.awt.event.*;

class Numpad extends Panel implements ActionListener {

Button n0, n1, n2, n3, n4, n5, n6, n7, n8, n9, point, equal;

Button plus, minus, multiply, divide;

Button blank_1, blank_2, clear, scientific;

TextField display;

String op1, op2, result;

double dop1, dop2, dresult;

String op_flag;

String data;

boolean decimal = false;

boolean flag_scientific = true;

public Numpad(TextField display) {

this.display = display;

setLayout(new GridLayout(0, 4));

// this.setFont(new Font("Times New Roman", Font.PLAIN, 15));

n0 = new Button("0");

n0.setActionCommand("zero");

n0.addActionListener(this);

n1 = new Button("1");

n1.setActionCommand("one");

n1.addActionListener(this);

71
n2 = new Button("2");

n2.setActionCommand("two");

n2.addActionListener(this);

n3 = new Button("3");

n3.setActionCommand("three");

n3.addActionListener(this);

n4 = new Button("4");

n4.setActionCommand("four");

n4.addActionListener(this);

n5 = new Button("5");

n5.setActionCommand("five");

n5.addActionListener(this);

n6 = new Button("6");

n6.setActionCommand("six");

n6.addActionListener(this);

n7 = new Button("7");

n7.setActionCommand("seven");

n7.addActionListener(this);

n8 = new Button("8");

n8.setActionCommand("eight");

n8.addActionListener(this);

n9 = new Button("9");

n9.setActionCommand("nine");

n9.addActionListener(this);

72
point = new Button(".");

point.setActionCommand("point");

point.addActionListener(this);

equal = new Button("=");

equal.setActionCommand("equal");

equal.addActionListener(this);

plus = new Button("+");

plus.setActionCommand("plus");

plus.addActionListener(this);

minus = new Button("-");

minus.setActionCommand("minus");

minus.addActionListener(this);

multiply = new Button("x");

multiply.setActionCommand("multiply");

multiply.addActionListener(this);

divide = new Button("/");

divide.setActionCommand("divide");

divide.addActionListener(this);

blank_1 = new Button("");

blank_1.setActionCommand("blank_1");

blank_1.addActionListener(this);

blank_2 = new Button("");

blank_2.setActionCommand("blank_2");

blank_2.addActionListener(this);

73
clear = new Button("C");

clear.setActionCommand("clear");

clear.addActionListener(this);

scientific = new Button("SCI /STD");

scientific.setActionCommand("scientific");

scientific.addActionListener(this);

add(n7);

add(n8);

add(n9);

add(divide);

add(n4);

add(n5);

add(n6);

add(multiply);

add(n1);

add(n2);

add(n3);

add(minus);

add(point);

add(n0);

add(equal);

add(plus);

add(blank_1);

add(clear);

add(blank_2);

add(scientific);

74
public String getDisplayText() {

return display.getText().toString();

public void setDisplay(String text) {

display.setText(text);

display.setEditable(false);

public void clearDisplay() {

setDisplay("");

data = "";

public void changeAdvanced(boolean toAdvanced) {

if (toAdvanced) {

plus.setLabel("sin");

plus.setActionCommand("sin");

minus.setLabel("cos");

minus.setActionCommand("cos");

multiply.setLabel("tan");

multiply.setActionCommand("tan");

divide.setLabel("log");

divide.setActionCommand("log");

} else {

plus.setLabel("+");

plus.setActionCommand("plus");

minus.setLabel("-");

minus.setActionCommand("minus");

multiply.setLabel("x");

75
multiply.setActionCommand("multiply");

divide.setLabel("/");

divide.setActionCommand("divide");

public void actionPerformed(ActionEvent e) {

data = getDisplayText();

switch (e.getActionCommand()) {

case "zero":

setDisplay(data + "0");

break;

case "one":

setDisplay(data + "1");

break;

case "two":

setDisplay(data + "2");

break;

case "three":

setDisplay(data + "3");

break;

case "four":

setDisplay(data + "4");

break;

case "five":

setDisplay(data + "5");

break;

case "six":

setDisplay(data + "6");

break;

76
case "seven":

setDisplay(data + "7");

break;

case "eight":

setDisplay(data + "8");

break;

case "nine":

setDisplay(data + "9");

break;

case "point":

if (decimal == false) {

setDisplay(data + ".");

decimal = true;

break;

case "plus":

decimal = false;

op1 = data;

op_flag = "plus";

clearDisplay();

break;

case "minus":

decimal = false;

op1 = data;

op_flag = "minus";

clearDisplay();

break;

case "multiply":

decimal = false;

op1 = data;

op_flag = "multiply";

77
clearDisplay();

break;

case "divide":

decimal = false;

op1 = data;

op_flag = "divide";

clearDisplay();

break;

case "clear":

decimal = false;

clearDisplay();

break;

case "scientific":

if (flag_scientific) {

changeAdvanced(true);

flag_scientific = false;

} else {

changeAdvanced(false);

flag_scientific = true;

break;

case "sin":

op1 = data;

setDisplay(String.valueOf(Math.sin(Double.valueOf(op1))));

break;

case "cos":

op1 = data;

setDisplay(String.valueOf(Math.cos(Double.valueOf(op1))));

break;

78
case "tan":

op1 = data;

setDisplay(String.valueOf(Math.tan(Double.valueOf(op1))));

break;

case "log":

op1 = data;

setDisplay(String.valueOf(Math.log(Double.valueOf(op1))));

break;

case "equal":

decimal = false;

switch (op_flag) {

case "plus":

op2 = data;

clearDisplay();

dop1 = Double.parseDouble(op1);

dop2 = Double.parseDouble(op2);

dresult = dop1 + dop2;

result = String.valueOf(dresult);

setDisplay(result);

op_flag = "";

break;

case "minus":

op2 = data;

clearDisplay();

dop1 = Double.parseDouble(op1);

dop2 = Double.parseDouble(op2);

dresult = dop1 - dop2;

result = String.valueOf(dresult);

setDisplay(result);

79
op_flag = "";

break;

case "multiply":

op2 = data;

clearDisplay();

dop1 = Double.parseDouble(op1);

dop2 = Double.parseDouble(op2);

dresult = dop1 * dop2;

result = String.valueOf(dresult);

setDisplay(result);

op_flag = "";

break;

case "divide":

op2 = data;

clearDisplay();

dop1 = Double.parseDouble(op1);

dop2 = Double.parseDouble(op2);

dresult = dop1 / dop2;

result = String.valueOf(dresult);

setDisplay(result);

op_flag = "";

break;

80
class Calculator extends Frame {

TextField display;

public Calculator() {

display = new TextField();

display.setFont(new Font("Times New Roman", Font.PLAIN, 30));

setLayout(new BorderLayout());

add(new Numpad(display), BorderLayout.CENTER);

add(display, BorderLayout.NORTH);

setVisible(true);

setSize(290, 300);

setResizable(false);

setTitle("Calculator");

setLocationRelativeTo(null);

addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

dispose();

});

public class Main {

public static void main(String[] args) {

new Calculator();

81
OUTPUT:

RESULT:
An event driven programming for creating a standard / scientific calculator in Java was
successfully implemented.

82
12. MINI PROJECT – ONLINE JAVA QUIZ APPLICATION

Date:

AIM:

To create an online Java quiz application using Swing.

ALGORITHM:

1. Write a Swing based graphics application to create a container to display the components

of the quiz program.

2. Store the questions and its correct responses on a hash map.

3. Display each question and provide the user with multiple choice answers as responses to

the questions.

4. Similarly iterate through all the questions and store the user responses.

5. When all questions have been answered, create a new window to display the correct

responses to the questions along with the responses marked by the users.

6. On the same window, display the total quiz score obtained based on the number of correct

responses entered by the user.

83
PROGRAM:

Quiz.java

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import javax.swing.event.*;

import java.util.*;

class Quiz extends JFrame implements ActionListener {

JPanel panel;

JPanel panelresult;

JRadioButton choice1;

JRadioButton choice2;

JRadioButton choice3;

JRadioButton choice4;

ButtonGroup bg;

JLabel lblmess;

JButton btnext;

String[][] questions;

String[][] answers;

int qaid;

HashMap<Integer, String> map;

Quiz() {

initializedata();

setTitle("Programming Quiz");

setDefaultCloseOperation(EXIT_ON_CLOSE);

int windowWidth = 430;

int windowHeight = 350;

setSize(windowWidth, windowHeight);

84
Point center = GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint();

setLocation(center.x - windowWidth / 2, center.y - windowHeight / 2);

setResizable(false);

Container cont = getContentPane();

cont.setLayout(null);

cont.setBackground(Color.GRAY);

bg = new ButtonGroup();

choice1 = new JRadioButton("Choice1", true);

choice2 = new JRadioButton("Choice2", false);

choice3 = new JRadioButton("Choice3", false);

choice4 = new JRadioButton("Choice4", false);

bg.add(choice1);

bg.add(choice2);

bg.add(choice3);

bg.add(choice4);

lblmess = new JLabel("Choose a correct anwswer");

lblmess.setForeground(Color.BLUE);

lblmess.setFont(new Font("Arial", Font.BOLD, 11));

btnext = new JButton("Next Question");

btnext.setForeground(Color.PINK);

btnext.addActionListener(this);

panel = new JPanel();

panel.setBackground(Color.LIGHT_GRAY);

panel.setLocation(10, 10);

panel.setSize(400, 300);

panel.setLayout(new GridLayout(6, 2));

panel.add(lblmess);

panel.add(choice1);

panel.add(choice2);

panel.add(choice3);

panel.add(choice4);

85
panel.add(btnext);

cont.add(panel);

setVisible(true);

qaid = 0;

readqa(qaid);

public void actionPerformed(ActionEvent e) {

if (btnext.getText().equals("Next Question")) {

if (qaid < 9) {

map.put(qaid, getSelection());

qaid++;

readqa(qaid);

} else {

map.put(qaid, getSelection());

btnext.setText("Show Answers");

} else if (btnext.getText().equals("Show Answers"))

new Report();

public void initializedata() {

// questions array stores pairs of question and its answers

questions = new String[10][5];

questions[0][0] = "How do you run a Java program on the command prompt?";

questions[0][1] = "javac JavaProgram";

questions[0][2] = "java JavaProgram";

86
questions[0][3] = "javac JavaProgram.java";

questions[0][4] = "None";

questions[1][0] = "What is the range of short data type in Java?";

questions[1][1] = "-128 to 127";

questions[1][2] = "-32768 to 32767";

questions[1][3] = "-2147483648 to 2147483647";

questions[1][4] = "None of the above";

questions[2][0] = "How to read a character from the keyboard?";

questions[2][1] = "char c=System.read()";

questions[2][2] = "char c=System.in.read()";

questions[2][3] = "char c=(char)System.read()";

questions[2][4] = "char c=(char)System.in.read()";

questions[3][0] = "Which one is a single-line comment?";

questions[3][1] = "/...";

questions[3][2] = "//...";

questions[3][3] = "/*...";

questions[3][4] = "/*...*/";

questions[4][0] = "How do you declare an integer variable x?";

questions[4][1] = "int x";

questions[4][2] = "x as Integer";

questions[4][3] = "Int[] x";

questions[4][4] = "None is correct.";

questions[5][0] = "How do you convert a string of number to a number?";

questions[5][1] = "int num=Integer.parseInt(str_num)";

questions[5][2] = "int num=str_num.toInteger()";

questions[5][3] = "int num=(int)str_num";

87
questions[5][4] = "int num=(Integer)str_num";

questions[6][0] = "Which of these keywords is not a part of exception handling?";

questions[6][1] = "try";

questions[6][2] = "finally";

questions[6][3] = "thrown";

questions[6][4] = "catch";

questions[7][0] = "How to do exit a loop?";

questions[7][1] = "Using exit";

questions[7][2] = "Using break";

questions[7][3] = "Using continue";

questions[7][4] = "Using terminate";

questions[8][0] = "What is the correct way to allocate a one-dimensional array?";

questions[8][1] = "int[size] arr=new int[]";

questions[8][2] = "int arr[size]=new int[]";

questions[8][3] = "int[size] arr=new int[size]";

questions[8][4] = "int[] arr=new int[size]";

questions[9][0] = "What is the correct way to allocate a two-dimensional array?";

questions[9][1] = "int[size][] arr=new int[][]";

questions[9][2] = "int arr=new int[rows][cols]";

questions[9][3] = "int arr[rows][]=new int[rows][cols]";

questions[9][4] = "int[][] arr=new int[rows][cols]";

// answers array stores pairs of question and its correct answer

answers = new String[10][2];

answers[0][0] = "How do you run a Java program on the command prompt?";

answers[0][1] = "java JavaProgram";

88
answers[1][0] = "What is the range of short data type in Java?";

answers[1][1] = "-32768 to 32767";

answers[2][0] = "How to read a character from the keyboard?";

answers[2][1] = "char c=(char)System.in.read()";

answers[3][0] = "Which one is a single-line comment?";

answers[3][1] = "//...";

answers[4][0] = "How do you declare an integer variable x?";

answers[4][1] = "int x";

answers[5][0] = "How do you convert a string of number to a number?";

answers[5][1] = "int num=Integer.parseInt(str_num)";

answers[6][0] = "Which of these keywords is not a part of exception handling?";

answers[6][1] = "thrown";

answers[7][0] = "How to do exit a loop?";

answers[7][1] = "Using break";

answers[8][0] = "What is the correct way to allocate a one-dimensional array?";

answers[8][1] = "int[] arr=new int[size]";

answers[9][0] = "What is the correct way to allocate a two-dimensional array?";

answers[9][1] = "int[][] arr=new int[rows][cols]";

// create a map object to store pairs of question and selected answer

map = new HashMap<Integer, String>();

89
public String getSelection() {

String selectedChoice = null;

Enumeration<AbstractButton> buttons = bg.getElements();

while (buttons.hasMoreElements()) {

JRadioButton temp = (JRadioButton) buttons.nextElement();

if (temp.isSelected()) {

selectedChoice = temp.getText();

return (selectedChoice);

public void readqa(int qid) {

lblmess.setText(" " + questions[qid][0]);

choice1.setText(questions[qid][1]);

choice2.setText(questions[qid][2]);

choice3.setText(questions[qid][3]);

choice4.setText(questions[qid][4]);

choice1.setSelected(true);

public void reset() {

qaid = 0;

map.clear();

readqa(qaid);

btnext.setText("Next Question");

public int calCorrectAnswer() {

int qnum = 10;

int count = 0;

90
for (int qid = 0; qid < qnum; qid++)

if (answers[qid][1].equals(map.get(qid)))

count++;

return count;

public class Report extends JFrame {

Report() {

setTitle("Result");

int windowWidth = 850;

int windowHeight = 550;

setSize(windowWidth, windowHeight);

Point center =

GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint();

setLocation(center.x - windowWidth / 2, center.y - windowHeight / 2);

setBackground(Color.WHITE);

setResizable(false);

addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

dispose();

reset();

});

Draw d = new Draw();

add(d);

setVisible(true);

class Draw extends Canvas {

public void paint(Graphics g) {

int qnum = 10;

91
int x = 10;

int y = 20;

for (int i = 0; i < qnum; i++) {

// print the 1st column

g.setFont(new Font("Arial", Font.BOLD, 12));

g.drawString(i + 1 + ". " + answers[i][0], x, y);

y += 30;

g.setFont(new Font("Arial", Font.PLAIN, 12));

g.drawString(" Correct answer : " + answers[i][1], x, y);

y += 30;

g.drawString(" Your answer : " + map.get(i), x, y);

y += 30;

// print the 2nd column

if (y > 400) {

y = 20;

x = 450;

// Show number of correct answers

int numc = calCorrectAnswer();

g.setColor(Color.BLUE);

g.setFont(new Font("Arial", Font.BOLD, 14));

g.drawString("Number of Correct Answers : " + numc, 300, 500);

92
QuizProgram.java

public class QuizProgram {

public static void main(String args[]) {

new Quiz();

93
OUTPUT:

94
RESULT:

The Java application for online quiz using Swing was implemented successfully.

95

You might also like