IntroductiontoJava-ActivityBook
IntroductiontoJava-ActivityBook
KA
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
R
KA
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R
Introduction to Java
Activity Book
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
R
KA
R
SA
Trademark Acknowledgements
A
R
IT
All products are registered trademarks of their respective organizations.
R
Introduction to Java_AB/18-M03-V1.0
Copyright ©NIIT. All rights reserved.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
COURSE DESIGN-LAB GUIDE
Table of Contents
Chapters
Activity
R
Problem Statement
KA
Prerequisite
R
Solution
SA
Exercises
Additional Exercises
A
R
IT
R
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Table of Contents
R
Exercise 1---------------------------------------------------------------------------- 1.4
KA
Exercise 2---------------------------------------------------------------------------- 1.4
Exercise 3---------------------------------------------------------------------------- 1.5
R
Exercise 4---------------------------------------------------------------------------- 1.5
SA
Exercise 5---------------------------------------------------------------------------- 1.5
Additional Exercises ------------------------------------------------------------------- 1.6
Exercise 1---------------------------------------------------------------------------- 1.6
A
R
Exercise 2---------------------------------------------------------------------------- 1.6
IT
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Chapter 3 – Working with Conditional and Loop Constructs
R
Exercises ---------------------------------------------------------------------------------- 3.6
KA
Exercise 1 ---------------------------------------------------------------------------- 3.6
R
Exercise 2 ---------------------------------------------------------------------------- 3.6
SA
Exercise 3 ---------------------------------------------------------------------------- 3.6
Exercise 4 ---------------------------------------------------------------------------- 3.6
Exercise 5 ---------------------------------------------------------------------------- 3.7
A
Additional Exercises-------------------------------------------------------------------- 3.8
R
Exercise 1 ---------------------------------------------------------------------------- 3.8
IT
R
-A
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Additional Exercises ------------------------------------------------------------------- 5.7
Exercise 1---------------------------------------------------------------------------- 5.7
R
Problem Statement ----------------------------------------------------------------- 6.6
KA
Solution ------------------------------------------------------------------------------ 6.6
Exercises --------------------------------------------------------------------------------- 6.9
R
Exercise 1---------------------------------------------------------------------------- 6.9
SA
Exercise 2---------------------------------------------------------------------------- 6.9
Exercise 3---------------------------------------------------------------------------- 6.9
A
R
Chapter 7 – Working with Regular Expressions
IT
R
-A
Activity 8.1: Working with Input Stream and Output Stream ---------------- 8.2
Problem Statement ----------------------------------------------------------------- 8.2
Prerequisite -------------------------------------------------------------------------- 8.2
Solution ------------------------------------------------------------------------------ 8.2
Exercises --------------------------------------------------------------------------------- 8.6
Exercise 1---------------------------------------------------------------------------- 8.6
Exercise 2---------------------------------------------------------------------------- 8.6
Additional Exercises ------------------------------------------------------------------- 8.7
Exercise 1---------------------------------------------------------------------------- 8.7
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
R
KA
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R
Overview of Java
CHAPTER 1
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Activity 1.1: Creating and Executing a Class
Problem Statement
ProGame Inc. has recently introduced a new department that develops games. For this, the organization has
hired junior programmers. They have been assigned a project to develop the HangmanGame application in
Java. They need to create the class structure for the Hangman game. In addition, they need to write code to
display a menu that a user will use to play the game, view the game instructions, or exit the game. Further,
the menu should also accept the input from the player. Help the programmers to do the needful.
R
KA
Solution
R
To achieve the preceding requirements, the programmers need to perform the following steps:
SA
1. Create a Java application, HangmanGame.
2. Create a package, game, in the Java application, HangmanGame.
3. Create a class, Hangman, in the package, game.
A
R
4. Replace the code in the Hangman.java file with the following code:
IT
R
package game;
import java.util.Scanner;
-A
int option;
Scanner sc = new Scanner(System.in);
30
System.out.println("---------Menu---------");
System.out.println("1. Play");
52
System.out.println("2. Instructions");
System.out.println("3. Exit");
00
}
public static void main(String[] args)
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
After executing the preceding code, the following output is displayed:
---------Menu---------
1. Play
2. Instructions
3. Exit
Note
Refer to the toolbook to create and execute the Java application in NetBeans.
R
KA
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Exercises
Exercise 1
Alchem Inc. is an emerging company in Singapore. Recently, the organization has seen a huge growth
following which the management has decided to hire 100 employees. In order to organize the details of an
ever rising count of employees in an efficient manner, the management has asked Shawn, the Head of the IT
department, to create an application named EmployeeBook. This application will store details, such as,
employee ID, employee name, department, designation, date of joining, date of birth, marital status, and date
of marriage. This application will be useful for storing the details of the employees in an organized manner.
It will also be useful in updating and accessing the personal details of the employees quickly. To achieve
R
this, the application must provide the functionality to store the personal employee data that includes the
KA
employee name, mobile number, address, marital status, and date of birth. Ask the students to identify the
following components:
R
Various classes
SA
Class members
Access modifiers
A
Exercise 2
R
IT
Create a class named EmployeeDetails for the EmployeeBook application and display a menu similar to the
R
following menu:
-A
---------Menu---------
01
1. Enter Data
2. Update Data
02
3. Display Data
4. Exit
30
In addition, the application should accept a menu input from the user, such as 1, 2, 3, and 4.
19
R
Note
Create a Java application, EmployeeBook, in NetBeans and create a package, alchem.
Further, create the EmployeeDetails class for exercise 2, inside the alchem package.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Exercise 3
Predict the output of the following code:
class JumbledGame {
final int choice;
public static void main(String[] args) {
JumbledGame obj1 = new JumbledGame ();
System.out.println(obj1.choice);
}
}
Exercise 4
R
Write a program to create a class named SampleClass. The SampleClass class should contain a variable
KA
named counter and assign it the value, 1. Declare the counter variable as public. Create a method
named Display() in the class. The Display() method should print the value of the counter variable.
R
Create an object and access the Display() method using the object.
SA
Exercise 5
Create a Reservation class with a member variable, TicketID, and a method, ShowTicket(). A
A
R
constructor should initialize the TicketID variable, and the ShowTicket() method should display its
IT
value. In addition, create an object of the Reservation class to call these methods.
R
-A
Note
01
Create a Java application named Exercises and create packages with chapter names,
such as chapter01 and chapter02, in NetBeans. Further, in the Exercises application,
02
create the classes for the exercises, 4 and 5, respectively, inside the package,
30
chapter01.
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Additional Exercises
Exercise 1
ServeYourMoney bank offers various services to its customers. The bank has branches all over the country,
and therefore, each branch has a unique id. The bank stores the details of its customers, such as customer
name, account number, address, phone number, and email address. In addition, the bank stores the various
details of its employees, such as employee name, employee id, address, phone number, and email id. The
bank offers its customers a choice of accounts, such as savings account and current account. Ask the students
to identify the various classes, their member variables, and data types.
R
Exercise 2
KA
Create a Grocery class with a member variable, weight, and two methods, weightNow() and
R
checkWeight(). The weightNow() method should initialize the weight variable and the
SA
checkWeight() method should display its value. In addition, create an object of the Grocery class to call
the preceding methods.
A
R
Note
IT
You need to create a folder by your name in D:\IJ. In addition, create a Java
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
R
KA
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R
Implementing Operators
CHAPTER 2
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Activity 2.1: Working with Operators
Problem Statement
David needs to write a program to calculate the net payable salary. The program will take basic salary as an
input from the user and calculate the total salary along with the following components:
HRA, which is 50% of the basic salary
Special allowance, which is 75% of the basic salary
R
PF deduction, which is 12% of the basic salary
KA
After calculating the preceding salary components, the net payable salary should be displayed. Help David to
R
perform the preceding requirement.
SA
Note
Net payable salary = (basic+HRA+special allowance) -PF
A
R
IT
R
-A
Solution
To solve the preceding requirement, David needs to perform the following steps:
01
package calculator;
19
import java.util.Scanner;
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
hra=(50*basicsalary)/100;
specialallowance=(75*basicsalary)/100;
pf=(12*basicsalary)/100;
netpayablesalary=basicsalary+hra+specialallowance-pf;
R
5. Compile and execute the SalaryCalculator Java application.
KA
After executing the preceding code, the following output is displayed:
R
Enter your basic salary:
SA
Once you provide the basic salary as 5000, the following output is displayed:
A
Basic salary =5000 R
HRA =2500
Special allowance =3750
IT
PF =600
R
------------------------
-A
Note
30
Refer the toolbook to create and execute the Java application in NetBeans.
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Exercises
Exercise 1
John needs to write a program to calculate the total distance travelled by a vehicle. The program will take
initial velocity, acceleration, and time as input from the user. To calculate the distance, John can use the
following formula:
Distance = ut + (at2) /2
Here, u is the initial velocity (meters per second), a is the acceleration (meters per second2), and t is the time
(seconds). Help John to perform the preceding task.
R
KA
Exercise 2
R
Mary needs to write a program to calculate the volume of a cylinder. The program will take radius and height
SA
of cylinder as input from the user. To calculate the volume, Mary can use the following formula:
Volume = πr2h
A
Here, r is the radius of the cylinder, h is the height of the cylinder, and value of pie (π) is 22/7. Help Mary
R
to perform the preceding task.
IT
R
Exercise 3
-A
Arnold wants to write a program to convert the temperature given in Celsius to Fahrenheit. The program will
01
take temperature in Celsius as input from the user. To calculate the temperature, Arnold can use the
following formula:
02
F = C * 9/5 +32
30
Here, C is the temperature in Celsius and F is the temperature in Fahrenheit. Help Arnold to perform the
52
preceding task.
00
Exercise 4
19
Write a program to perform the bitwise AND, OR, NOT, and XOR operations on the numbers, 5 and 9.
R
Exercise 5
Consider the following expression:
4 * 4 + 8 / 4
When Sam executes the preceding expression by using the Java code, he gets an output value of 18.
However, he wants that the output should be 12. Help Sam to achieve the preceding task.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Note
You need to create the classes of exercises 1, 2, 3, 4, and 5 inside the package,
chapter02 inside the application, Exercises.
R
KA
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Additional Exercises
Exercise 1
Write a program to display the postfix and prefix values of the given number, 5, by using increment
operators.
Exercise 2
Write a program to perform left shift and right shift operations for 2 by 2 bits. In addition, perform unsigned
right shift for -2 by 24 bits.
R
KA
Note
R
You need to create the classes of exercises 1 and 2 inside the package,
SA
chapter02, in the application, AdditionalExercises.
A
R
IT
R
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
R
KA
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Activity 3.1: Working with Conditional
Constructs
Problem Statement
Peter wants to display the following menu when the Hangman game starts:
1. Play Game
2. View Instructions
3. Exit Game
R
KA
Thereafter, he wants a user to enter a choice, such as 1, 2, or 3. In addition, he wants the respective methods,
playGame(), instructGame(), or exitGame(), to be invoked according to the user’s input, 1, 2, or 3,
R
respectively. Help Peter to achieve the preceding requirement.
SA
Prerequisite
To perform the activity, you need to use the Activity1.1.txt file.
A
R
IT
Solution
R
To achieve the preceding requirement, Peter needs to perform the following steps:
-A
4. Replace the code in the Hangman.java file with the code in the Activity1.1.txt file.
30
5. Add the following code snippet after the comment, // Switch Case, within the showMenu() method
in the Hangman.java file:
52
switch(option)
00
{
19
case 1: playGame();
break;
R
case 2: instructGame();
break;
case 3: exitGame();
break;
default: System.out.println("Incorrect menu option");
showMenu();
break;
}
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
6. Add the following code snippet after the comment, // Method definition, in the Hangman.java
file:
R
{
KA
System.out.println("exitGame method is invoked");
System.exit(0);
R
}
SA
7. Compile and execute the HangmanGame Java application.
After executing the application, the following output is displayed:
A
R
---------Menu---------
IT
1. Play
2. Instructions
R
3. Exit
-A
Note
Refer to the toolbook to create and execute the Java application in NetBeans.
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Activity 3.2: Working with Loop Constructs
Problem Statement
In the Hangman game, Peter wants a user to enter a letter. On the basis of the user’s input, he wants to check
whether the letter is present in the word or not. For this, he decides to compare the letter entered by the user
with each letter of the corresponding word. If the letter is present in the word, it should display an
appropriate message. In addition, he wants the menu to be displayed till the user wants to guess a letter. Help
Peter to achieve the preceding requirement.
R
KA
Prerequisite
R
To perform the activity, you need to use the Activity3.1.txt file.
SA
Solution
To achieve the preceding requirement, Peter needs to perform the following steps:
A
1. Ensure that the HangmanGame Java application is open and active.
R
IT
2. Ensure that the Hangman.java file is open.
R
4. Replace the code in the Hangman.java file with the code in the Activity3.1.txt file.
01
5. Add the following code snippet after the comment, // Instance variable, in the Hangman.java
file:
02
6. Replace the code after the comment, //playGame functionality, within the playGame() method
52
do
{
System.out.print("\nEnter Your Guess: ");
input = sc.nextLine();
for(i=0;i<word.length();i++)
{
if(word.charAt(i) == input.charAt(0))
{
flag=1;
}
}
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
if(flag==1)
{
System.out.println("This letter is present in the word");
}
else
{
System.out.println("This letter is not present in the word");
}
}while(guess.equals("y")||guess.equals("Y"));
R
KA
7. Compile and execute the HangmanGame Java application.
R
After executing the application, the following output is displayed:
SA
---------Menu---------
1. Play
2. Instructions
3. Exit
A
R
IT
Choose the option:
R
Note
Refer to the toolbook to create and execute the Java application in NetBeans.
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Exercises
Exercise 1
In the EmployeeBook application, David wants to display the following menu when the application starts:
1. Enter Data
2. Display Data
3. Exit
Thereafter, he wants a user to enter a choice, such as 1, 2, or 3. Based on the input provided by the user, he
wants the respective methods, enterData(), displayData(), or exitMenu(), to be invoked according
R
to the user’s input, 1, 2, or 3, respectively. Help David to achieve the preceding requirement.
KA
R
Note
SA
You need to modify the class, EmployeeDetails, inside the package, alchem, in the
application, EmployeeBook, created in Chapter 1.
A
R
IT
Exercise 2
R
-A
12345
1234
02
123
30
12
52
1
00
Exercise 3
19
Exercise 4
Write a program to accept a number from a user and display all the prime numbers between one and the
number entered by the user.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Exercise 5
Write a program to accept two numbers and check if the first is divisible by the second. In addition, an error
message should be displayed if the second number is zero.
Note
You need to create the classes of exercises, 2, 3, 4, and 5, inside the package,
chapter03, in the application, Exercises.
R
KA
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Additional Exercises
Exercise 1
Write a program to print the table of five.
Note
You need to create the class of exercise 1 inside the package, chapter03, in the
application, AdditionalExercises.
R
KA
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
R
KA
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Activity 4.1: Manipulating Arrays and Strings
Problem Statement
In the Hangman game, when a user decides to play the Hangman game, the numbers of dashes or blanks that
are equal to the length of a word are displayed. To implement this, Peter needs to store a group of words,
randomly pick a word, calculate the length of the word, and finally displays the number of dashes or blanks.
In addition, he wants to implement the functionality that takes an alphabetical character as an input from the
user, check if the character entered by the user exists in the corresponding word, and display the letter in the
R
appropriate dashes. However, if the character doesn’t exist in the word, it is added to the list of missed
KA
letters. Help Peter to achieve the preceding requirement.
R
Prerequisite
SA
To perform the activity, you need to use the Activity3.2.txt file.
Solution
A
R
IT
To achieve the preceding requirement, Peter needs to perform the following steps:
R
4. Replace the code in the Hangman.java file with the code in the Activity3.2.txt file.
02
5. Replace the statement after the comment, // Instance variable, with the following code snippet,
30
6. Add the following code snippet after the comment, // import statements:
19
import java.util.Random;
R
7. Replace the code after the comment, //playGame functionality, within the playGame() method
in the Hangman.java file:
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
len = word[rnd].length();
char[] newString = new char[len];
R
KA
System.out.print("\n\nEnter your guess: ");
String ch = input.nextLine().toLowerCase();
count++;
R
SA
for (i = 0; i < len; i++)
{
if (word[rnd].charAt(i) == ch.charAt(0))
A
{ R
newString[i] = word[rnd].charAt(i);
flag = 1;
IT
}
R
}
-A
if (flag == 0)
{
01
flag=1;
wrgString.append(ch + ",");
02
System.out.println(newString);
52
if (word[rnd].equals(temp))
{
19
choice = input.nextLine();
if (choice.equalsIgnoreCase("y"))
{
playGame();
}
else
{
showMenu();
}
}
}while(flag!=0);
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Note
The method, int nextInt(int), of java.util.Random class is used generate a
random number between -1 and the value passed as argument to the method.
---------Menu---------
1. Play
R
2. Instructions
KA
3. Exit
R
Choose the option:
SA
Once you provide the option as 1, the following output is displayed:
_ _ _ _ _ _ _ _
A
R
IT
Enter your guess:
R
-A
01
Note
Number of dashes may vary as per the functionality of the game.
02
30
52
a
19
Note
The preceding output will only be displayed if the entered letter is present in the word
corresponding to the dashes. However, if the letter is not present in the word
corresponding to dashes it will show the following output:
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Exercises
Exercise 1
In the EmployeeBook application, David wants to implements the following functionalities:
When user selects the option to enter data, the employee details, such as employee ID, employee name,
department, designation, date of joining, date of birth, marital status, and date of marriage should be
captured. However, date of marriage can be captured only if the employee is married.
When user selects the option to view data, the employee id of the employee for which the data needs to
view should be entered and validated. If the employee id is correct, the details should be displayed else
an error message should be displayed.
R
KA
When user selects the option to exit, the application must terminate.
Help David to implement the preceding functionalities.
R
SA
Note
You need to modify the class, EmployeeDetails inside the package, alchem, in the
application, EmployeeBook created in Chapter 3.
A
R
IT
R
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Additional Exercises
Exercise 1
Sam has been assigned the task to create a Java application that a user can use to know the degrees of
directions shown by a compass. In this application, he needs to restrict the user to specify the directions as
NORTH, SOUTH, EAST, WEST, NORTHEAST, SOUTHEAST, SOUTHWEST, or NORTHWEST. Create
an enum and declare a class to test the enum that Sam can use in his application.
Note
R
You need to create the class for exercises 1 inside the package, chapter04, in the
KA
application, AdditionalExercises.
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
R
KA
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R
Implementing
Inheritance and
Polymorphism
CHAPTER 5
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Activity 5.1: Implementing Inheritance and
Polymorphism
Problem Statement
The management of LearnMore University is planning to automate the University management system.
Therefore, Steve Wilkinson, the programmer, has decided to create a Java program that accepts the student
details, such as the first name, last name, age, course enrolled, and student ID. In addition, he also needs to
accept the employee details, such as first name, last name, age, salary, department name, designation, and
employee ID. Steve must ensure the reusability of code. The program must offer a choice to accept either the
R
student’s or employee’s details. Help Steve to develop the program.
KA
R
Solution
SA
To achieve the preceding requirements, Steve needs to perform the following steps:
1. Create a Java application, Information.
2. Create a package, university, in the application, Information.
A
R
3. Create a class, Person, inside the package, university.
IT
4. Replace the code in Person.java with the following code:
R
package university;
-A
import java.util.Scanner;
01
String firstName;
30
String lastName;
int age;
52
{
Scanner input = new Scanner(System.in);
19
firstName = input.nextLine();
System.out.println("Enter the Last Name");
lastName = input.nextLine();
System.out.println("Enter the Age");
age = input.nextInt();
}
}
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
6. Replace the code in Employee.java with the following code:
package university;
import java.util.Scanner;
class Employee extends Person
{
double Salary;
String desg;
String dept;
public void getDetail()
{
super.getDetail();
Scanner input = new Scanner(System.in);
System.out.println("Enter the Professional Details");
R
System.out.println("Enter the Department");
KA
dept = input.nextLine();
System.out.println("Enter the Designation");
R
desg = input.nextLine();
SA
System.out.println("Enter the Salary");
Salary = input.nextInt();
showDetail();
}
A
R
public void showDetail()
IT
{
System.out.println("The details entered are: \n");
R
}
}
52
package university;
R
import java.util.Scanner;
class Student extends Person
{
String University;
String stream;
int StudentID;
public void getDetail()
{
super.getDetail();
Scanner input = new Scanner(System.in);
System.out.println("Enter the Academic Details");
System.out.println("Enter the Course enrolled");
stream = input.nextLine();
System.out.println("Enter the Student ID");
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
StudentID = input.nextInt();
showDetail();
}
public void showDetail()
{
System.out.println("The details entered are: \n");
System.out.println("First Name: " + super.firstName);
System.out.println("Last Name: " + super.lastName);
System.out.println("Age: " + super.age);
System.out.println("Course Enrolled: " + stream);
System.out.println("Student ID: " + StudentID);
}
}
R
9. Create a class, MainMenu, inside the package, university.
KA
10. Replace the code in MainMenu.java with the following code:
R
package university;
SA
import java.util.Scanner;
public class MainMenu
{
A
public static void main(String[] args) { R
Scanner choice = new Scanner(System.in);
System.out.println("Menu");
IT
System.out.println("1. Student Details");
R
switch (a)
{
02
case 1:
Student st = new Student();
30
st.getDetail();
break;
52
case 2:
Employee emp1 = new Employee();
00
emp1.getDetail();
break;
19
}
}
R
Menu
1. Student Details
2. Employee Details
Enter the choice:
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Note
After specifying the choice as 1 or 2, you can enter the desired details for a student or
an employee, respectively.
Note
Refer to the toolbook to create and execute the Java application in NetBeans.
R
KA
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Exercises
Exercise 1
Furniture and Fittings Company (FFC) manufactures chairs and bookshelves. The customers provide their
specifications for the desired furniture item to the company. The furniture items in the company have similar
characteristics, such as price, width, and height. However, for some furniture items, specific details need to
be provided by the customers. Recently, the business of the company has increased significantly. To handle
the increased customer’s orders, FFC has decided to computerize the order processing system. For this, you
need to develop a Java program that accepts the furniture attributes from the customers, as per the specified
furniture items, such as bookshelves and chairs. You need to develop the program to accept and display the
R
various choices of customers.
KA
Exercise 2
R
Create a library management system program that will be used to store the details of the software books and
SA
hardware books. For software books, the various pieces of information, such as the author name, title, price,
stock, software version, software name, and number of pages, should be accepted.
A
For hardware books, the various pieces of information, such as the author name, title, price, number of pages,
R
stock, hardware category, and publisher, should be accepted. After accepting the details in either of the book
IT
categories, the entered details must be displayed. You need to ensure that code reusability is implemented in
R
the program.
-A
01
Note
02
You need to create the classes of exercises 1 and 2 inside the package, chapter05,
30
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Additional Exercises
Exercise 1
Define a FixedAccount class containing the method, calculateInterest(), which calculates the
interest on the balance for a fixed account. In addition, extend the FixedAccount class and override the
calculateInterest()method to calculate the interest for the savings account. The interest rate for the
fixed and savings account are different.
Note
R
KA
You need to create the classes of exercise 1 inside the package, chapter05, in the
application, AdditionalExercises.
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
R
KA
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R
Handling Errors
CHAPTER 6
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Activity 6.1: Exception Handling
Problem Statement
In the Hangman game, Peter wants to implement exception handling, such that if a user enters a menu input
other than 1, 2, or 3 in the game menu option, an appropriate user-defined exception should be generated. In
addition, a user-defined exception should be generated if the player inputs multiple characters, instead of a
single character to identify the possible alphabet in the word.
R
KA
Prerequisite
To perform the activity, you need to use the Activity4.1.txt file.
R
SA
Solution
To achieve the preceding requirements, Peter needs to perform the following steps:
1. Ensure that the HangmanGame Java application is open and active.
A
R
2. Create a new exception class named WrongInputException in the game package.
IT
3. Replace the code in the WrongInputException file with the following code:
R
-A
package game;
public class WrongInputException extends RuntimeException
01
{
WrongInputException()
02
{
System.out.println("Please provide a single character only..!!");
30
}
}
52
00
package game;
public class MenuInputException extends RuntimeException
{
MenuInputException()
{
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
9. Replace the statements after the comment, // try-catch block, within the showMenu() method
with the following statements:
option=0;
try
{
option = sc.nextInt();
}
catch(RuntimeException e)
{
System.out.println("Please provide a valid numeric input");
showMenu();
}
R
// Switch Case
switch(option)
KA
{
case 1: playGame();
R
break;
SA
case 2: instructGame();
break;
case 3: System.exit(0);
break;
A
R
default:
IT
try
R
{
throw new MenuInputException();
-A
}
01
catch (Exception e)
{
02
showMenu();
}
30
}
52
10. Replace the statements after the comment, //Implement user defined exception, within the
playGame() method with the following code snippet:
00
19
try
{
R
String ch = input.nextLine().toLowerCase();
if(ch.length()!=1)
{
throw new WrongInputException();
}
count++;
for (i = 0; i < len; i++)
{
if (word[rnd].charAt(i) == ch.charAt(0))
{
newString[i] = word[rnd].charAt(i);
flag = 1;
}
}
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
if (flag == 0)
{
flag=1;
wrgString.append(ch + ",");
System.out.println("\nMisses: " + wrgString);
}
System.out.println(newString);
temp = new String(newString);
if (word[rnd].equals(temp))
{
System.out.println("---------- Congrats :) You won ------------");
System.out.println("Do you want to play again (Y/N)");
R
choice = input.nextLine();
KA
if (choice.equalsIgnoreCase("y"))
{
R
playGame();
SA
}
else
{
A
showMenu(); R
}
IT
}
R
}
-A
catch (WrongInputException e)
{
01
//System.out.println(e);
flag = 1;
02
}
}
30
while(flag!=0);
52
---------Menu---------
R
1. Play
2. Instructions
3. Exit
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Once you provide the option as 7, the following output is displayed:
_ _ _ _ _
R
KA
Enter your guess:
R
Once you specify the guess as aaa, the following output is displayed:
SA
Please provide a single character only..!!
Note
01
Note
00
Refer to the toolbook to create and execute the Java application in NetBeans.
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Activity 6.2: Implementing Assertions
Problem Statement
Create a calculator application in Java that will accept two numbers. Further, the calculator application
should be able to perform the following operations one at a time on the two numbers:
Addition
Subtraction
R
KA
Multiplication
Division
R
You need to implement assertions and assert that both the numbers should be greater than 0. Further, the
SA
operator used to perform the calculations should only be +,-, *, or, /.
A
Solution R
To achieve the preceding requirements, you need to perform the following steps:
IT
1. Create a Java application, CalculatorApplication.
R
package calculator;
52
import java.util.Scanner;
class CalculatorApp
00
{
19
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
assert ((op.equals("+")) || (op.equals("-")) || (op.equals("*")) ||
(op.equals("/"))) : "The operator is not valid.";
if (op.equals("+"))
{
res = num1 + num2;
}
else if (op.equals("-"))
{
R
} else
KA
{
res = num2 - num1;
}
R
}
SA
else if (op.equals("*"))
{
A
res = num1 * num2; R
}
IT
else if (op.equals("/"))
R
{
-A
else
{
02
System.out.println("Wrong operator");
}
30
}
00
Once you enter the 1st number as 8, the following output is displayed:
Once you enter the 2nd number as 5, the following output is displayed:
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Once you enter the operator as &, the following output is displayed:
Note
The line number in the CalculatorApp.java:21 statement may vary.
R
KA
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Exercises
Exercise 1
Consider the scenario of the EmployeeDetails application. In this application, David needs to implement
user-defined exceptions for the following cases:
If the menu input entered by the user is less than 1 or greater than 3, an appropriate message should be
displayed to the user and the application must restart.
The employee id entered does not start with the alphabet “e”.
R
KA
Note
You need to modify the class, EmployeeDetails, inside the package, alchem, in the
R
application, EmployeeBook, created in Chapter 4.
SA
A
Exercise 2 R
Sammy is a programmer at NewAxis Technologies. He needs to write a program, which will accept the
IT
employee details from a user. A user should be able to enter the name, contact details, and age. The
R
minimum and maximum ages are 20 and 55, respectively. If the age of an employee is less than 20 or greater
than 55, a user-defined exception should be thrown. Help Sammy to perform this task.
-A
01
Exercise 3
02
Create a program to divide two numbers. The program should provide the functionality, such that if a user
tries to perform the division operation by 0, the program should terminate with a customized message.
30
52
Note
00
You need to create the classes of exercises 2 and 3 inside the package, chapter06,
inside the application, Exercises.
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
R
KA
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Activity 7.1: Processing Strings Using Regex
Problem Statement
Create a method, which should have the email-id and password fields as parameters. When a user calls the
method, the email and password entered by the user should be validated. The email-id field should be
specified in the format, such as xyz@xyz.co.in or xyz@xyz.com.
In addition, the format of the password should adhere to the following conventions:
R
There should be one special character.
KA
There should be one uppercase letter.
R
There should be one lowercase letter.
SA
The password should be eight characters long.
Prerequisite
A
To perform the activity, you need to use the LoginForm.txt file.
R
IT
Solution
R
-A
To achieve the preceding requirements, you need to perform the following steps:
01
5. Replace the code in the LoginForm.java file with the code in the LoginForm.txt file.
6. Add the following code after the //Validation Code comment:
00
9]+)$");
Matcher matcher = pattern.matcher(email);
R
boolean emailValidator=matcher.matches();
Pattern passwordPattern = Pattern.compile("^(?=.*[0-9])(?=.*[a-z])(?=.*[A-
Z])(?=.*[@#$%^&+=]).{8,}$");
Matcher matcherPassword = passwordPattern.matcher(password);
boolean passwordValidator=matcherPassword.matches();
if(emailValidator==true && passwordValidator==true)
{
System.out.println("Email Id and password are in correct
format...");
return true;
}
else if(emailValidator==false)
{
System.out.println("Email Id is in incorrect format...");
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
return false;
}
else if(passwordValidator==false)
{
System.out.println("Password is in incorrect format...");
return false;
}
else
{
System.out.println("Email Id or Password is in incorrect
format...");
return false;
}
R
7. Compile and execute the LoginFormApplication application.
KA
After executing the application, the following output is displayed:
R
SA
A
The Output of the LoginFormApplication Application R
Once you have typed the text, xyz@xyz, in the Email-id and AAss11## in the Password and click the
IT
Enter button. The following output is displayed:
R
-A
01
02
Now type the text xyz@xyz.com in the Email-id and AAss11 in the Password and click the Enter
52
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Exercises
Exercise 1
Write a program that accepts a Web portal name from the user. In addition, the program should validate the
format of the Web portal name. The Web portal name should have the following fields:
Protocol, such as https or http.
Domain, such as xyz.
The top level domain should be more than one character, such as .co.
R
KA
Note
You need to create the classes of the exercise 1 inside the package,
R
chapter07, inside the application, Exercises.
SA
A
R
IT
R
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Additional Exercises
Exercise 1
You need to develop an application that accepts a name and contact number as inputs from the user. In
addition, you need to validate these inputs based on the following constraints:
The name should contain only letters.
The contact number should contain only numeric values in the (xxx-xxxx-xxxx) format.
R
Note
KA
You need to create the classes of the exercise 1 inside the package,
chapter07, in the application, AdditionalExercises.
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
R
KA
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Activity 8.1: Working with Input Stream and
Output Stream
Problem Statement
David is a Java developer at MacroBusiness Inc. He has been assigned a task to develop the application to
find the factorial. In this application, he needs to implement the following functionalities:
The User should be presented with a menu, which has the options to Calculate factorial, view the
instructions, view user’s factorial, and exit.
R
Every time, when the user play the game, their score should be updated in a text file. In addition, if a
KA
player decides to view the factorial Score, it should be displayed.
R
Help David to achieve this task.
SA
Prerequisite
To perform the activity, you need to use the FileOperation.txt, GameMenu.txt, GetScore.txt, Factorial.txt
and Main.txt files.
A
R
IT
Solution
R
To achieve the preceding task, David needs to perform the following steps:
-A
5. Replace the code in the GameMenu.java file with the code in the GameMenu.txt file.
52
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
18. Add the following code after the //Reading Data comment:
name = player.toLowerCase();
String factorial = "";
String line;
R
for (int i = 0; i < txt.length; i++) {
if (txt[i].equals(stringSearch)) {
KA
factorial=txt[i+1];
R
SA
}
}
}
A
R
}
IT
R
catch (IOException e) {
-A
}
01
return factorial;
02
19. Add the following code after the //Writing Data comment:
30
}
19
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Once you enter the choice 1. The following output is displayed:
R
KA
The Output of the GameApp Application
Once you have typed user name NIIT in the Enter Name field and and 12 in the Enter Number field
R
and press Enter. The following output is displayed:
SA
A
R
IT
R
-A
01
02
30
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
And if you enter the choice as 3. The following output is displayed:
R
The Output of the GameApp Application
KA
Once you enter the Name to be Searched as NIIT. The following output is displayed:
R
SA
A
R
IT
R
-A
01
Once you Enter the Choice 4 . The following output will be displayed:
30
52
00
19
R
Note
You can enter a Number less than 20 in the Enter Number field.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Exercises
Exercise 1
You need to write a program which provides an option to either input the book details or display the book
details. In addition, on selecting the input option, the book details, such as the book name, author name, and
price, should be accepted and written into a text file. Further, if the display option is selected, all the book
details should be displayed.
Exercise 2
R
You need to develop an application that accepts the name of a file and the word to be searched in that file.
KA
Based on the input that the user has provided, the application should display the number of occurrences of
that word in the file.
R
SA
Note
A
In order to perform the search in a document in the exercise, 2, you can use an existing
R
document.
IT
R
-A
01
Note
02
You need to create the classes of the exercises, 1 and 2, inside the package,
chapter08, inside the application, Exercises.
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Additional Exercises
Exercise 1
Write a program that accepts an absolute file path, such as D:\Textfile.txt, and the content to write into the
file from the user. The program should continue accepting the content from the user until the user inputs the
text, end.
Note
R
You need to create the classes of the exercise, 1, inside the package,
KA
chapter08, in the application, AdditionalExercises.
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
R
KA
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.