Students Lab Manual CS112
Students Lab Manual CS112
Lab Manual
Programming 2
CS 112
Student ID:
Student Name:
January 2019
Acknowledgment
Dr. Barzaiq
January 2019
Declaration
The resources used to prepare and write the lab manual
are:
2. No part of this work has been copied from any other source or
person except where explicitly stated otherwise by reference or
acknowledgment.
Date of signature
ASSIGNMENT DECLARATION FORM
(Individual Assignment)
2. No part of this work has been copied from any other source or person
except where explicitly stated otherwise by reference or
acknowledgment.
Course Code
Course Title
Student ID
Student Name:
Signature of student
Date of signature
Contents
Programming 2 (Java) ...........................................................Error! Bookmark not defined.
Instructions: ..................................................................................................................1
Lab 001: Review of Programming 1 ................................................................................ 11
Objective: ................................................................................................................. 11
Examples: ................................................................................................................. 11
Example 1‐ Analyzing a program or project: ............................................................. 11
Example 2‐ Strictly identical arrays for one‐dimensional: .......................................... 13
Exercise ‐ Strictly identical arrays for two‐dimensional: ................................................ 14
Homework – identical arrays for one‐dimensional: ...................................................... 15
Challenge Question ‐ identical arrays for two‐dimensional:........................................... 16
Lab 002: Chapter 9: OBJECTS AND CLASSES (part 1) ......................................................... 17
Objective: ................................................................................................................. 17
Example – Circle class: ............................................................................................... 17
Exercise ‐ Rectangle class: .......................................................................................... 18
Homework – Stock and Random classes: ..................................................................... 18
Challenge Question – Using GregorianCalendar and Date classes: ................................. 19
Lab 003: Chapter 9: OBJECTS AND CLASSES (part 2) ......................................................... 21
Example – StopWatch class: ....................................................................................... 21
Exercise ‐ Account class: ............................................................................................ 23
Homework ‐ Fan class: ............................................................................................... 24
Lab 004: Chapter 10 ‐ OBJECT‐ORIENTED THINKING ......................................................... 25
Objective: ................................................................................................................. 25
Example – StackOfIntegers class (Section 10.6): ........................................................... 25
Exercise – StackOfStrings Class: .................................................................................. 28
Homework* – Prime factors and prime numbers: ........................................................ 30
Lab 005: Inheritance & Polymorphism ............................................................................ 31
Objective: ................................................................................................................. 31
Examples: ................................................................................................................. 31
Example 1‐ Inheritance: ......................................................................................... 31
Exercises: ................................................................................................................. 32
Exercise 1‐ UML Digram: ........................................................................................ 32
Homework: .............................................................................................................. 32
Homework 1‐ Implement the previous five classes: .................................................. 32
Challenge Question: .................................................................................................. 32
Question 1‐ Remove duplicates: ............................................................................. 32
Lab 006: Inheritance & Polymorphism (continuted) ......................................................... 34
Objective: ................................................................................................................. 34
Examples: ................................................................................................................. 34
Example 1‐ Runtime Polymorphism: ....................................................................... 34
Exercises: ................................................................................................................. 35
Exercise 1‐ Add a subclass: ..................................................................................... 35
Homework: .............................................................................................................. 35
Homework 1‐ Account class:................................................................................... 35
Challenge Question: .................................................................................................. 38
Question 1‐ Shows extra info: ................................................................................. 38
Lab 007: Exception Handling and File I/O ........................................................................ 39
Objective: ................................................................................................................. 39
Examples: ................................................................................................................. 39
Example 1‐ Exception Handling: .............................................................................. 39
Exercises: ................................................................................................................. 40
Exercise 1‐ Exception Handling (continued): ............................................................. 40
Homework: .............................................................................................................. 40
Homework 1‐ MergeFiles: ...................................................................................... 40
Challenge Question: .................................................................................................. 41
Question 1‐ Read and Save: .................................................................................... 41
Lab 008: Abstract Classes & Interfaces ............................................................................ 42
Objective: ................................................................................................................. 42
Examples: ................................................................................................................. 42
Example 1‐ Abstract Classes and Methods: .............................................................. 42
Exercises: ................................................................................................................. 46
Exercise 1‐ Retrieve the areas and perimeters of objects: ......................................... 46
Homework: .............................................................................................................. 46
Homework 1‐ Square class: .................................................................................... 46
Challenge Question: .................................................................................................. 46
Question 1‐ Shuffles an ArrayList: ........................................................................... 46
Lab 009: Abstract Classes & Interfaces (continued) .......................................................... 47
Objective: ................................................................................................................. 47
Examples: ................................................................................................................. 47
Example 1‐ Edible interface: ................................................................................... 47
Exercises: ................................................................................................................. 49
Exercise 1‐ Java.math.BigInteger.compareTo() Method:............................................ 49
Homework: .............................................................................................................. 50
Homework 1‐ The Colorable interface: .................................................................... 50
Challenge Question: .................................................................................................. 50
Question 1‐ Enable the Course class cloneable: ........................................................ 50
Lab 010: JAVAFX BASICS ................................................................................................ 52
Objective: ................................................................................................................. 52
Examples: ................................................................................................................. 52
Example 1‐ Shapes: ................................................................................................ 52
Exercises: ................................................................................................................. 53
Exercise 1‐ Random shapes: ................................................................................... 53
Exercise 2‐ Tic‐tac‐toe board: ................................................................................. 54
Homework: .............................................................................................................. 54
Homework 1‐ Display flags: .................................................................................... 54
Challenge Question: .................................................................................................. 54
Question 1‐ Resizable rectangle: ............................................................................. 54
Lab 011: Event‐Driven Programming and Animations ....................................................... 56
Objective: ................................................................................................................. 56
Examples: ................................................................................................................. 56
Example 1‐ Rotate a rectangle: ............................................................................... 56
Example 2‐ Simple calculator: ................................................................................. 57
Exercises: ................................................................................................................. 60
Exercise 1‐ Guess a number: ................................................................................... 60
Homework: .............................................................................................................. 60
Homework 1‐ Move the ball: .................................................................................. 60
Challenge Question: .................................................................................................. 61
Question 1‐ Move the ball inside the boundary: ....................................................... 61
Lab 012: Event‐Driven Programming and Animations (continue) ....................................... 62
Objective: ................................................................................................................. 62
Examples: ................................................................................................................. 62
Example 1‐ Rotate a rectangle left and right: ........................................................... 62
Example 2‐ Simple calculator: ................................................................................. 64
Exercises: ................................................................................................................. 66
Exercise 1‐ Guess a number with help: .................................................................... 66
Exercise 2‐ Rotate a rectangle with random color: .................................................... 66
Lab 013: JAVAFX UI CONTROLS AND MULTIMEDIA........................................................... 67
Objective: ................................................................................................................. 67
Examples: ................................................................................................................. 67
Example 1‐ Select geometric figures: ....................................................................... 67
Exercises: ................................................................................................................. 69
Exercise 1‐ Registration Form: ................................................................................ 69
Homework: .............................................................................................................. 70
Homework 1‐ Move a text: ..................................................................................... 70
Challenge Question: .................................................................................................. 70
Question 1‐ Active registration form: ...................................................................... 70
Lab 014: JAVAFX Key and Mouse Events ......................................................................... 72
Objective: ................................................................................................................. 72
Examples: ................................................................................................................. 72
Example 1‐ Move a circle using keys: ....................................................................... 72
Example 2‐ Move a circle using mouse: ................................................................... 73
Exercises: ................................................................................................................. 75
Exercise 1‐ Enter and display a string: ...................................................................... 75
Exercise 2‐ Display the mouse position: ................................................................... 75
Homework: .............................................................................................................. 75
Homework 1‐ Change color using a mouse: ............................................................. 75
Challenge Question: .................................................................................................. 76
Question 1‐ Two movable vertices and their distances: ............................................. 76
Feedback: .................................................................................................................... 77
Lab 001: Review of Programming 1
Objective:
‐ This lab is reviewing what you have studied in the first course of programming 1 (CS
111)
‐ Reviewing how to analyze a code and how to write the code by using different
components: Print statement, Input from an user, Primitive types, Variables,
Selection instruction, Loops, Methods, Single dimensional array and multi‐
dimensional array.
Examples:
Example 1‐ Analyzing a program or project:
Write an equals method that reads two arrays and displays these messages above.
// Invoke method
equals(first, second);
}
// Define method
public static void equals(int[] first, int[] second) {
if (first.length != second.length)
System.out.println("The size of the two arrays are not
equals");
else
{
for (int i = 0; i < first.length; i++) {
if (first[i] != second[i])
{
System.out.println("The two arrays are not
strictly identical arrays");
break;
}
if(i == first.length‐1)
System.out.println("The two arrays are strictly
identical arrays");
}
}
}
}
Hint: The solution of this challenge is quite similar to the solution of homework question.
■ Two double data fields named width and height that specify the width and height of the
rectangle. The default values are 1 for both width and height.
■ A constructor that creates a rectangle with the specified width and height.
Draw the UML diagram for the class and then implement the class. Write a test program that
creates two Rectangle objects—one with width 4 and height 40 and the other with width 3.5
and height 35.9. Display the width, height, area, and perimeter of each rectangle in this
order.
وارتفاع4 أحدهما بعرض- اكتب برنامج اختبار يقوم بإنشاء كائنني مستطيالت. للفصل ثم نفذ الفصلUML ارسم مخطط
. اعرض عرض كل مستطيل وارتفاعه ومساحته ومحيطه بهذا الترتيب.35.9 وارتفاع3.5 واآلخر بعرض40
Homework – Stock and Random classes:
Design a class named Stock that contains:
■ A double data field named previousClosingPrice that stores the stock price for the previous
day.
■ A double data field named currentPrice that stores the stock price for the current time.
■ An integer data field named ID that stores the identifier number of stock.
■ A constructor that creates a stock with the specified symbol, name, and ID.
)( الذي يُرجع النسبة املئوية التي تم تغييرها من سعر اإلغالق السابق إلى السعر الحاليgetChangePercent األسلوب املسمى
Draw the UML diagram for the class and then implement the class. Write a test program that
■ creates a Random object from the Random class (java.util.Random). –We will use this
object for the ID number of Stock between (0 to 100)‐
■ asks a user for the name and symbol of Stock. So, you should create two string variables in
the test program.
■ creates a Stock object with the stock symbol (from the user), the name of symbol (from
the user), and ID (from Random object by using nextInt(100) method).
■ asks the user for the previous closing price and the current price. Note: Don't create two
variables for them. You can use the stock object to assign the values of these two variables
from the user.
■ finally, displays the stock name, the stock symbol, the stock ID, and the price‐change
percentage.
1- Display the current year, month, and day. )( من فئة التاريخtoString اعرض التاريخ الحالي باستخدام طريقة
2- Display the current date by using the toString() method from the Date class. الذي- اعرض الوقت الحالي
3- Display the current time –which is used to display the number of milliseconds‐ by ‐يُستخدم لعرض عدد املللي ثانية
)( منgetTime باستخدام طريقة
using getTime() method from the Date class. We will use it in the step 17. سنستخدمه في الخطوة.فئة التاريخ
17
4- Display the current year by using get(GregorianCalendar.YEAR) method from the
GregorianCalendar class. GregorianCalendar من فئةget (GregorianCalendar.YEAR) عرض السنة الحالية باستخدام طريقة
اعرض السنة الحالية
get باستخدام طريقة
5- Display the current year by using get(GregorianCalendar.MONTH) method from the
(GregorianCalen
منdar.MONTH)
GregorianCalendar class. Note: this method ‐which is used for month‐ starts from 0
فئة to 11 (0 indicates January). You must take care about this issue for adding 1 in order
GregorianCalen
هذه: ملحوظة.dar to display 1 for January.
الطريقة "التي تُستخدم
إلى0 للشهر" تبدأ من 6- Display the current Day by using get(GregorianCalendar.DAY_OF_MONTH) method
إلى0 )يشير الرقم11
يجب أن.(شهر يناير from the GregorianCalendar class. من فئةget (GregorianCalendar.DAY_OF_MONTH) اعرض اليوم الحالي باستخدام طريقة
تهتم بهذه املشكلة GregorianCalendar
1 لعرض1 إلضافة
لشهر يناير
GregorianCalendar من فئةget (GregorianCalendar.DAY_OF_WEEK) اعرض األسبوع الحالي باستخدام طريقة
The time after adding 1 millisecond(s) : Mon Jan 07 11:05:17 AST 2019
The time after adding 10 millisecond(s) : Mon Jan 07 11:05:17 AST 2019
The time after adding 100 millisecond(s) : Mon Jan 07 11:05:17 AST 2019
The time after adding 1000 millisecond(s) : Mon Jan 07 11:05:18 AST 2019
The time after adding 10000 millisecond(s) : Mon Jan 07 11:05:27 AST 2019
The time after adding 100000 millisecond(s) : Mon Jan 07 11:06:57 AST 2019
The time after adding 1000000 millisecond(s) : Mon Jan 07 11:21:57 AST 2019
The time after adding 10000000 millisecond(s) : Mon Jan 07 13:51:57 AST 2019
The time after adding 100000000 millisecond(s) : Tue Jan 08 14:51:57 AST 2019
The time after adding 1000000000 millisecond(s) : Sat Jan 19 00:51:57 AST 2019
The time after adding 10000000000 millisecond(s) : Fri May 03 04:51:57 AST 2019
The time after adding 100000000000 millisecond(s) : Wed Mar 09 20:51:57 AST 2022
Lab 003: Chapter 9: OBJECTS AND CLASSES (part 2)
'
■ A method named start() that resets the startTime to the current time.
■ A method named stop() that sets the endTime to the current time.
■ A method named getElapsedTime() that returns the elapsed time for the stopwatch in
milliseconds.
Draw the UML diagram for the class and then implement the class. Write a test program that
measures the execution time of sorting 100,000 numbers using selection sort.
Hi is91.63 a
a
selectionSort(numbers);
stopWatch.stop();
public StopWatch() {
startTime = System.currentTimeMillis();
}
StopWatch
‐startTime: long
‐endTime: long
+StopWatch()
+getStratTime(): long
+getEndTime(): long
+start()
+stop()
+getElapsedTime(): long
Exercise ‐ Account class:
Design a class named Account that contains:
account.withdraw(2500);
account.deposit(3000);
System.out.println("Balance is " + account.getBalance());
System.out.println("This account was created at " +
account.getDateCreated());
}
}
Class Account {
}
Homework ‐ Fan class:
■ Three constants named SLOW, MEDIUM, and FAST with the values 0, 1, and 2 to denote
the fan speed. للداللة على سرعة املروحة2 و1 و0 بقيمFAST وMEDIUM وSLOW ثالثة ثوابت تسمى
■ A private int data field named speed that specifies the speed of the fan (the default is
SLOW). SLOW يحدد سرعة املروحة )االفتراضي هوspeed حقل بيانات خاص يسمى
■ A private boolean data field named on that specifies whether the fan is on (the default is
false). false يحدد حقل البيانات املنطقية الخاص املسمى على ذلك ما إذا كانت املروحة قيد التشغيل )اإلعداد االفتراضي هو
■ A private double data field named radius that specifies the radius of the fan (the default is
4). 4 حقل بيانات مزدوج خاص يسمى نصف القطر الذي يحدد نصف قطر املروحة )االفتراضي هو
■ A string data field named color that specifies the color of the fan (the default is red).
حقل بيانات السلسلة املسمى اللون الذي يحدد لون املروحة )االفتراضي هو األحمر
■ The accessor and mutator methods for all four data fields.
طرق الوصول واملحول لجميع حقول البيانات األربعة
■ A no‐arg constructor that creates a default fan. ُمنشئ ال يستخدم إلنشاء مروحة افتراضية
■ A method named toString() that returns a string description for the fan. If the fan is on, the
method returns the fan speed, color, and radius in one combined string. If the fan is not on,
the method returns the fan color and radius along with the string “fan is off” in one
تقوم الطريقة بإرجاع سرعة املروحة واللون ونصف القطر في، إذا كانت املروحة قيد التشغيل. )( تقوم بإرجاع وصف سلسلة للمروحةtoString طريقة تسمى
combined string. سلسلة
فإن الطريقة تُرجع لون املروحة ونصف قطرها جنبًا إلى جنب مع السلسلة "املروحة متوقفة" في سلسلة واحدة مدمجة، إذا لم تكن املروحة قيد التشغيل.واحدة مدمجة
Draw the UML diagram for the class and then implement the class. Write a test program that
creates two Fan objects. Assign maximum speed, radius 10, color yellow, and turn it on to
the first object. Assign medium speed, radius 4, color red, and turn it off to the second
object. Display the objects by invoking their toString method.
قم بتعيني السرعة القصوى ونصف.Fan اكتب برنامج اختبار يقوم بإنشاء كائنني من عناصر. للفصل ثم نفذ الفصلUML ارسم مخطط
. واللون األحمر وأوقف تشغيله على الكائن الثاني4 عني السرعة املتوسطة ونصف القطر
ّ . واللون األصفر وتشغيله على الكائن األول10 القطر
الخاصة بهمtoString اعرض الكائنات عن طريق استدعاء طريقة
Fan
slow iint o
MEDIUMi int o
FAST i int o
speedi int o
o n ibooledu false
radius idouble 4
Color strings red
FanC
is iii eat it
setradius new radiusidoubled it o id
setColor newcolor istring i void
getspeedc i in t
get on C i booledh
get red u i sc i double
getColor C string
tostring it i string
Lab 004: Chapter 10 ‐ OBJECT‐ORIENTED THINKING
Objective:
■ To apply class abstraction to develop software (§10.2).
b. A private data field size to store the number of strings in the stack
f. A method push(String value) that stores value at the top of the stack. This method checks
if the stack is full before pushing to it. In case the stack is full, it
ii. creates a new elements array with double the current capacity
g. A method pop() that removes the string at the top of the stack and returns it. In case the
stack is empty, it returns "Stack is EMPTY"
h. A method peek() that returns the string at the top of the stack without removing it from
the stack. In case the stack is empty, it returns "Stack is EMPTY"
System.out.println();
}
1. Draw the UML diagram for the StackOfStrings class.
3. Use the test program shown on the following page which creates a StackOfStrings object,
and then allows the user to push, pop or peek at the stack.
4. Draw the UML diagram for the StackOfStrings object created in the test program.
import java.util.Scanner;
while (true) {
String s = input.nextLine();
switch (stackCommand) {
case "PSH":
stack.printStack();
break;
case "POP":
System.out.println(stack.pop());
stack.printStack();
break;
case "PEK":
System.out.println(stack.peek());
stack.printStack();
break;
case "STP":
System.exit(0)
default:
class StackOfStrings {
Write a program that prompts the user to enter a positive integer which is greater than
one and displays all its smallest factors in decreasing order. For example, if the integer is
140, the smallest factors are displayed as 7, 5, 2, 2. Use the StackOfIntegers class to store
the factors (e.g., 2, 2, 5, 7) and retrieve and display them in reverse order. After that, write a
program that displays all the prime numbers less than the number – which is used in the
prime factors (e.g: 140)‐ in decreasing order. Use the StackOfIntegers class to store the
prime numbers (e.g., 2, 3, 5, ...) and retrieve and display them in reverse order.
Examples:
Example 1‐ Inheritance:
Write a test program to run the below classes where class Teacher is a base class, class
PhysicsTeacher is a derived class which extends Teacher class as shown in UML digram.
class Teacher {
void does(){
System.out.println("Teaching");
Test.java
System.out.println(obj.collegeName);
System.out.println(obj.designation);
System.out.println(obj.mainSubject);
obj.does();
Output:
Beginnersbook
Teacher
Physics
Teaching
Exercises: ، عالوة على ذلك.لنفترض أن لدينا خمس فصول وهي فصول الشخص والطالب واملوظف والكلية واملوظفني
ونجعل أعضاء هيئة التدريس واملوظفني فئات فرعية، دعونا نجعل الطالب واملوظف فئات فرعية من األشخاص
Exercise 1‐ UML Digram: لهذه الفئات بنا ًء على اإلرشادات التاليةUML يرجى إنشاء مخطط.للموظف
Let us suppose we have five classes which are the Person, Student, Employee, Faculty, and
Staff Classes. Moreover, let us make Student and Employee as subclasses of Person, and
make Faculty and Staff as subclasses of Employee. Please create a UML digram for those
classes based on the following instructions:
أ( تتمتع فئة الشخص بالخصائص الخاصة التالية
a) The Person class has the following private properties:
وطرق الوصول إليها واملتحولString :االسم
name: String and its accessor and mutator methods
يحتوي فصل الطالب على األساليب والخصائص الخاصة التالية
b) The Student class has the following methods and private properties:
studentId: long
Constructor with two arguments: name, studentId
Override toString() in the Student class to return the name and studentId
c) The Employee class has the following private properties:
employeeId: int and its accessor and mutator methods
d) The Faculty class has the following methods and private properties:
rank: String
Constructor with three arguments: name, employeeId, rank
Override toString() in the Faculty class to return the name, employeeId, and rank
e) The Staff class has the following methods and private properties:
title: String
Constructor with three arguments: name, employeeId, title
Override toString() in the Staff class to return the name, employeeId, and title
Homework:
Homework 1‐ Implement the previous five classes:
a) Create the previous five classes in Exercise 1 in Java.
b) Write a test program to creates objects from the Student, Faculty and Staff classes,
and then invokes toString() methods for all three
Challenge Question:
Question 1‐ Remove duplicates:
Write a method that removes the duplicate elements from an array list of integers
using the following header:
public static void removeDuplicate(ArrayList<Integer> list)
Write a test program that prompts the user to enter 10 integers to a list and displays
the distinct integers separated by exactly one space. Here is a sample run:
Examples:
Example 1‐ Runtime Polymorphism:
Lets say we have a class Animal that has a method sound(). Since this is a generic
class so we can’t give it a implementation like: Roar, Meow, Oink etc. We had to give a
generic message
public class Animal{
Now lets say we a subclass of Animal class: Horse that extends Animal class. We can
provide the implementation to the same method like this:
@Override
System.out.println("Neigh");
obj.sound();
Output:
Neigh
Exercises:
Exercise 1‐ Add a subclass:
Create a subclass of Animal class: Cat.
Create a a sound function with a massage “Meow’’ inside Cat Class that includes a
sound function.
Call Sound method in Cat class by the reference variable of Animal class.
Homework:
Homework 1‐ Account class:
Update the below the Account class as follows:
a) Add a new data field name of the String type to store the name of the customer.
b) Add a new constructor that constructs an account with the specified name, id, and
balance.
c) Add a new data field named transactions whose type is ArrayList that stores the
transaction for the accounts.
e) Modify the withdraw and deposit methods to add a transaction to the transactions
array list.
f) All other properties and methods are the same as in the Account class below.
g) Write a test program that creates an Account with annual interest rate 1.5%,
balance 1000 , id 1122 , and name George . Deposit $30, $40, and $50 to the
account and withdraw $5, $4, and $2 from the account.
h) Print an account summary that shows account holder name, interest rate, balance,
and all transactions.
Here is Account class :
class Account {
private int id = 0;
public Account() {
this();
this.id = id;
this.balance = balance;
return this.id;
return this.balance;
return annualInterestRate;
return this.dateCreated.toString();
this.id = id;
this.balance = balance;
}
this.annualInterestRate = annualInterestRate;
this.balance ‐= amount;
this.balance += amount;
account.setAnnualInterestRate(4.5);
account.withdraw(2500.0);
account.deposit(3000.0);
}
Challenge Question:
Question 1‐ Shows extra info:
The point (h) in HomeWork1 is a bonus question which requires to print an account
summary that shows account holder name, interest rate, balance, and all transactions.
Lab 007: Exception Handling and File I/O
Objective:
‐ To declare exceptions in a method header.
‐ To throw exceptions in a method.
‐ To write a try‐catch block to handle exceptions.
‐ To discover file/directory properties, to delete and rename files/directories, and to
create directories using the File class.
‐ To write data to a file using the PrintWriter class.
‐ To read data from a file using the Scanner class.
‐ To develop a program that replaces text in a file.
‐ To read data from the Web.
Examples:
Example 1‐ Exception Handling:
The following examples shows how Exception Handling works:
public class MethodCallStackDemo {
System.out.println("Enter main()");
methodA();
System.out.println("Exit main()");
System.out.println("Enter methodA()");
try {
System.out.println(1 / 0);
} finally {
System.out.println("finally in methodA()");
System.out.println("Exit methodA()");
Output
Enter main()
Enter methodA()
finally in methodA()
at MethodCallStackDemo.methodA(MethodCallStackDemo.java:11)
at MethodCallStackDemo.main(MethodCallStackDemo.java:4)
Exercises:
Exercise 1‐ Exception Handling (continued):
What will be the output of the previous example if it is correct?
Homework:
Homework 1‐ MergeFiles:
1. Design a class named MergeFiles
3. In NetBeans, go to Run > Set Project Configuration > Customize… > Arguments. In
the field in front of Arguments type the following:
file1.txt file2.txt mergedFile.txt
4. Now if you run MergeFiles from within NetBeans, it will run with those three
command line arguments
5. Run the program, and examine the resultant mergedFile.txt to ensure that the
program is working properly
6. Delete throws Exception from main() and try to run the program. You will receive an
error. Is this error due an unchecked exception or checked exception?
7. There is a try block, but no catch or finally blocks in the code. The program,
however, still works properly. Why is that?
Program Logic
f) Create an ArrayList object, names
g) Open file1.txt for reading using File and Scanner
h) Read the contents of file1.txt into the names object
i) Open file2.txt for reading using File and Scanner
j) Read the contents of file2.txt and add them to names
k) Sort names by first converting it to an array and then applying the built-in Arrays.sort()
method
l) Print the contents of the sorted array to mergedFile.txt using File and PrintWriter
m) Skip any duplicate names while printing
n) The MergedFiles class can be invoked as follows:
java MergeFiles file1.txt file2.txt mergedFile.txt
Challenge Question:
Question 1‐ Read and Save:
Create a Java program that reads from a file on the Web using the URL class and save the file
content in a local file.
Lab 008: Abstract Classes & Interfaces
Objective:
‐ To design and use abstract classes.
‐ To design and use abstract methods.
‐ To design the Rational class for processing rational numbers.
‐ To design and use ArrayList.
Examples:
Example 1‐ Abstract Classes and Methods:
Here is an example to show how abstract Classes and Methods use:
GeometricObject.java
protected GeometricObject() {
}
/** Construct a geometric object with color and filled value */
this.color = color;
this.filled = filled;
return color;
this.color = color;
return filled;
this.filled = filled;
return dateCreated;
@Override
Rectangle.java
public class Rectangle extends GeometricObject {
private double width;
private double height;
public Rectangle() {
}
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
/** Return width */
public double getWidth() {
return width;
}
/** Set a new width */
public void setWidth(double width) {
this.width = width;
}
/** Return height */
public double getHeight() {
return height;
}
/** Set a new height */
public void setHeight(double height) {
this.height = height;
}
@Override /** Return area */
public double getArea() {
return width * height;
}
@Override /** Return perimeter */
public double getPerimeter() {
return 2 * (width + height);
}
}
Circle.java
public class Circle extends GeometricObject {
private double radius;
public Circle() {
}
public Circle(double radius) {
this.radius = radius;
}
/** Return radius */
public double getRadius() {
return radius;
}
/** Set a new radius */
public void setRadius(double radius) {
this.radius = radius;
}
@Override /** Return area */
public double getArea() {
return radius * radius * Math.PI;
}
/** Return diameter */
public double getDiameter() {
return 2 * radius;
}
@Override /** Return perimeter */
public double getPerimeter() {
return 2 * radius * Math.PI;
}
/* Print the circle info */
public void printCircle() {
System.out.println("The circle is created " + getDateCreated() +
" and the radius is " + radius);
}
} r
Exercises:
Exercise 1‐ Retrieve the areas and perimeters of objects:
Write a test program to get areas and perimeters of both circle and rectangle objects in
the previous example.
Homework:
Homework 1‐ Square class:
Design a new Square class that extends the abstract GeometricObject class
(GeometricObject class is provided in Slides’ Chapter 13).
‐ Draw the UML diagram for the classes Square and GeometricObject and then
implement the Square class.
‐ Write a test program that prompts the user to one side of the square, a color, and a
Boolean value to indicate whether the square is filled.
Note: The program should create a Square object with one side and set the color and
filled properties using the input. Moreover, The program should display the area,
perimeter, color, and true or false to indicate whether it is filled or not.
Challenge Question:
Question 1‐ Shuffles an ArrayList:
Write the following method that shuffles an ArrayList of numbers:
public static void shuffle(ArrayList<Number> list)
Lab 009: Abstract Classes & Interfaces (continued)
Objective:
‐ To generalize numeric wrapper classes, BigInteger, and BigDecimal using the
abstract Number class.
‐ To specify common behavior for objects using interfaces.
‐ To define interfaces and define classes that implement interface.
‐ To define a natural order using the Comparable interface.
‐ To make objects cloneable using the Cloneable interface.
‐ To design the Rational class for processing rational numbers.
Examples:
Example 1‐ Edible interface:
We can use the Edible interface to specify whether an object is edible. This is accomplished
by letting the class for the object implement this interface (or inherit the interface) using the
implements keyword. For example, Chicken & Fruit implement the Edible interface in
TestEdible while Tiger is not.
Edible.java
public interface Edible {
TestEdible.java
public class TestEdible {
System.out.println(((Edible)objects[i]).howToEat());
System.out.println(((Animal)objects[i]).sound());
return weight;
this.weight = weight;
@Override
@Override
@Override
@Override
Output
Tiger: RROOAARR
Chicken: Fry it
Chicken: cock‐a‐doodle‐doo
Exercises:
Exercise 1‐ Java.math.BigInteger.compareTo() Method:
Write an example to shows the usage of math.BigInteger.compareTo() method.
Homework:
Homework 1‐ The Colorable interface:
Hint: you may use GeometricObject.java in Example 1 in Lab 018 and update
Square.java from Homework 1 in Lab 018.
Challenge Question:
Question 1‐ Enable the Course class cloneable:
Rewrite the Course class in Listing below to add a clone method to perform a deep copy on
the students field.
Course.java
this.courseName = courseName;
students[numberOfStudents] = student;
numberOfStudents++;
return students;
return numberOfStudents;
}
Lab 010: JAVAFX BASICS
Objective:
‐ To write a simple JavaFX program and understand the relationship among stages,
scenes, and nodes.
‐ To create user interfaces using panes, UI controls, and shapes.
Examples:
Example 1‐ Shapes:
Write a program that shows different types of geometric shapes.
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.GridPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Arc;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Ellipse;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.Line;
import javafx.scene.text.Text;
import javafx.stage.Stage;
/**
* The main method is only needed for the IDE with limited
* JavaFX support. Not needed for running from the command line.
*/
public static void main(String[] args) {
launch(args);
}
}
Exercises:
Exercise 1‐ Random shapes:
Reprogram the application in the example 1, so it displays shapes randomly.
Homework:
Homework 1‐ Display flags:
Write a program that displays four Flags selected from a deck of 10, The flag image files are
named 0.png, 1.png, …, 9.png and stored in the image directory.
Challenge Question:
Question 1‐ Resizable rectangle:
Write a program that displays rectangle that changes its size as long as the size of the screen
is changing
Examples:
Example 1‐ Rotate a rectangle:
Write a program that rotates a rectangle 15 degrees right when the Rotate button is clicked.
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
@Override
// Override the start method in the Application class
public void start(Stage primaryStage) {
StackPane stackPane = new StackPane();
Rectangle rectangle = new Rectangle(30, 30, 30, 60);
rectangle.setFill(Color.WHITE);
rectangle.setStroke(Color.BLACK);
stackPane.getChildren().add(rectangle);
/**
* The main method is only needed for the IDE with limited JavaFX support.
* Not needed for running from the command line.
*/
public static void main(String[] args) {
launch(args);
}
}
Rectangle rectangle;
double angle;
@Override
public void handle(ActionEvent event) {
angle += 15;
rectangle.setRotate(angle);
}
}
btSubtract.setOnAction(operationHandler);
btMultiply.setOnAction(operationHandler);
btDivide.setOnAction(operationHandler);
}
/**
* The main method is only needed for the IDE with limited
* JavaFX support. Not needed for running from the command line.
*/
public static void main(String[] args) {
launch(args);
}
}
@Override
public void handle(ActionEvent event) {
Object o = event.getSource();
if(o instanceof Button){
Button b = (Button)o;
String operation = b.getText();
String result;
if(operation.equals("Add")){
result = Double.parseDouble(tfNumber1.getText()) +
Double.parseDouble(tfNumber2.getText()) + "";
}
else if(operation.equals("Subtract")){
result = Double.parseDouble(tfNumber1.getText()) ‐
Double.parseDouble(tfNumber2.getText()) + "";
}
else if(operation.equals("Multiply")){
result = Double.parseDouble(tfNumber1.getText()) *
Double.parseDouble(tfNumber2.getText()) + "";
}
else {
result = Double.parseDouble(tfNumber1.getText()) /
Double.parseDouble(tfNumber2.getText()) + "";
}
tfResult.setText(result);
}
}
}
Exercises:
Exercise 1‐ Guess a number:
Write a program that prompt a user to enter a guess of a number and checks wither the
guess is correct or not.
Homework:
Homework 1‐ Move the ball:
Write a program that moves the ball in a pane. You should define a pane class for displaying
the ball and provide the methods for moving the ball left, right, up, and down.
Examples:
Example 1‐ Rotate a rectangle left and right:
Write a program that rotates a rectangle 15 degrees right or left when the Rotate button is
clicked.
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
@Override
// Override the start method in the Application class
public void start(Stage primaryStage) {
StackPane stackPane = new StackPane();
rectangle = new Rectangle(30, 30, 30, 60);
rectangle.setFill(Color.WHITE);
rectangle.setStroke(Color.BLACK);
stackPane.getChildren().add(rectangle);
/**
* The main method is only needed for the IDE with limited JavaFX support.
* Not needed for running from the command line.
*/
public static void main(String[] args) {
launch(args);
}
@Override
public void handle(ActionEvent event) {
angle += 15;
rectangle.setRotate(angle);
}
}
@Override
public void handle(ActionEvent event) {
angle ‐= 15;
rectangle.setRotate(angle);
}
}
}
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
btAdd.setOnAction(e ‐> {
tfResult.setText(Double.parseDouble(tfNumber1.getText()) +
Double.parseDouble(tfNumber2.getText()) + "");
});
btSubtract.setOnAction(e ‐> {
tfResult.setText(Double.parseDouble(tfNumber1.getText()) ‐
Double.parseDouble(tfNumber2.getText()) + "");
});
btMultiply.setOnAction(e ‐> {
tfResult.setText(Double.parseDouble(tfNumber1.getText()) *
Double.parseDouble(tfNumber2.getText()) + "");
});
btDivide.setOnAction(e ‐> {
tfResult.setText(Double.parseDouble(tfNumber1.getText()) /
Double.parseDouble(tfNumber2.getText()) + "");
});
}
/**
* The main method is only needed for the IDE with limited
* JavaFX support. Not needed for running from the command line.
*/
public static void main(String[] args) {
launch(args);
}
}
Exercises:
Exercise 1‐ Guess a number with help:
Write a program that prompt a user to enter a guess of a number and checks wither the
guess is correct or not. Add help button that gives a user a hint to increase or decrease the
guess.
Examples:
Example 1‐ Select geometric figures:
Write a program that draws various figures. The user selects a figure from a radio button
and uses a check box to specify whether it is filled.
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.CheckBox;
import javafx.scene.control.RadioButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Ellipse;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
rbCircle.setOnAction(e ‐> {
pane.getChildren().clear();
pane.getChildren().add(circle);
if (chkFill.isSelected()) {
circle.setFill(Color.BLACK);
}
else {
circle.setFill(Color.WHITE);
}
});
rbRectangle.setOnAction(e ‐> {
pane.getChildren().clear();
pane.getChildren().add(rectangle);
if (chkFill.isSelected()) {
rectangle.setFill(Color.BLACK);
}
else {
rectangle.setFill(Color.WHITE);
}
});
rbEllipse.setOnAction(e ‐> {
pane.getChildren().clear();
pane.getChildren().add(ellipse);
if (chkFill.isSelected()) {
ellipse.setFill(Color.BLACK);
}
else {
ellipse.setFill(Color.WHITE);
}
});
chkFill.setOnAction(e ‐> {
if (chkFill.isSelected()) {
circle.setFill(Color.BLACK);
rectangle.setFill(Color.BLACK);
ellipse.setFill(Color.BLACK);
}
else {
circle.setFill(Color.WHITE);
rectangle.setFill(Color.WHITE);
ellipse.setFill(Color.WHITE);
}
});
}
/**
* The main method is only needed for the IDE with limited
* JavaFX support. Not needed for running from the command line.
*/
public static void main(String[] args) {
launch(args);
}
}
Exercises:
Exercise 1‐ Registration Form:
Write a program for account registration.
Challenge Question:
Question 1‐ Active registration form:
Reprogram the exercise 1, so the form checks for validation when the button is clicked as
follows:
Phone‐ 8 digits.
Password‐ Contains at least one capital letter, one small letter, one digit and minimum
length is 8.
Confirm‐ Matches the entered password.
Examples:
Example 1‐ Move a circle using keys:
Write a program that moves a circle up, down, left, or right using the arrow keys.
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
// Creat a ball
Circle circle = new Circle(20);
Pane pane = new Pane();
@Override
public void start(Stage primaryStage) throws Exception {
circle.setCenterX(200);
circle.setCenterY(250);
pane.getChildren().add(circle);
/**
* The main method is only needed for the IDE with limited JavaFX support.
* Not needed for running from the command line.
*/
public static void main(String[] args) {
launch(args);
}
}
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
public class MoveCircleMouse extends Application implements EventHandler<MouseEvent>
{
// Creat a ball
Circle circle = new Circle(20);
Pane pane = new Pane();
@Override
public void start(Stage primaryStage) throws Exception {
circle.setCenterX(200);
circle.setCenterY(250);
pane.getChildren().add(circle);
primaryStage.setTitle("Move a circle");
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
}
circle.setCenterY(sceneY);
circle.setCenterX(sceneX);
}
/**
* The main method is only needed for the IDE with limited JavaFX support.
* Not needed for running from the command line.
*/
public static void main(String[] args) {
launch(args);
}
}
Exercises:
Exercise 1‐ Enter and display a string:
Write a program that receives a string from the keyboard and displays it on a pane. The
Enter key signals the end of a string while the Delete clears the pane.
Homework:
Homework 1‐ Change color using a mouse:
Write a program that displays the color of a circle as red when the mouse button is pressed
and as black when the mouse button is released.