public class Labrador extends Dog

Laboratory Booklet
IT 224
College Of Computer
Qassim University
Computer College
Laboratory
Booklet
IT 224 :
Visual Programming
Semester 1 – 1436/1437 H
Dr. Khalil Abu Zanouneh
Laboratory Booklet
IT 224
College Of Computer
LABORATORY POLICY AND GUIDLINES
Lab Rules and Regulations

The students should work separately.

Students are strictly prohibited from taking out any items (IC’s) from the
laboratory

Without permission from the Lab Supervisor.

The lab timetable must be strictly followed. Prior permission from the Lab

Supervisor must be obtained if any change is to be made.

Students must be punctual in the laboratory session.

Experiments must be completed within the given time.

All students are liable for any damage to equipment due to their own
negligence.

Static sensitive devices should be handled carefully.

All equipment, apparatus and tools must be RETURNED to their original
place after use.

Students are NOT allowed to work alone in the laboratory.

Please consult the Lab Supervisor if you are not sure how to operate the
laboratory equipment.

Report immediately to the Lab Supervisor any damages to equipment,
hazards, and potential hazards.

Please refer to the Lab Supervisor with any concerns
regarding the laboratory.
Laboratory Booklet
IT 224
College Of Computer
Tasks and Lab Grading Policy

Each student has to work on their own in order to be able to know how to
build a program from scratch.

Each student is supposed to know and work on the basic problem
solving algorithms.

Students in lab learn a lot from their own mistakes.

Students are not allowed to repeat the same mistakes.

Each student should know how to start, use and run the program.

Student s can receive hints on the questions after they were given a fair
amount of time to help them address their ideas.

Each student should demonstrate what was learned from each lab session
as they will be evaluated on the next lab.

Different possible solutions can be discussed and written to students where
they can see how questions can have many right answers.

Students should answer the lab questions separately which is part of the
evaluation.
Laboratory Booklet
IT 224
LAB 1
College Of Computer
Laboratory Booklet
IT 224
College Of Computer
Laboratory Booklet
IT 224
College Of Computer
Laboratory Booklet
IT 224
College Of Computer
Laboratory Booklet
IT 224
College Of Computer
package first1;
import java.util.Scanner;
public class Main {
// main method begins execution of Java application
public static void main( String args[] )
{
System.out.print( "Welcome to Java Programming!" );
System.out.println(" This is First Lab");
System.out.printf( "%s\n%s\n","Code: 224 IS ", " Visual Programming" );
System.out.println("enter number:");
Scanner key=new Scanner (System.in);
int x=key.nextInt();
int y=key.nextInt();
int sum=x+y;
System.out.println(" sum = "+sum+"ddddd");
/* this is
multiple-line
comments */
} // end method main
// } // end class Welcome1
}
Laboratory Booklet
IT 224
College Of Computer
package namedialog;
import javax.swing.JOptionPane;
public class NameDialog{
public static void main(String[] args{ )
String name = JOptionPane.showInputDialog("What is your name;)"?
String message = String.format("Welcom, %s", name;)
int age=Integer.parseInt(JOptionPane.showInputDialog(null,"plz enter your
ege;))":
JOptionPane.showMessageDialog(null, message;)
JOptionPane.showMessageDialog(null," you are "+age+" years old;)"
}
}
 Compiling and Executing Java Application through
NetBeans
LAB 2
 Introduction in java programming language
o Basic knowledge , comments ,identifiers , primitive types and first
program in java.
 Install Software that will be work in labs " NetBeans IDE ".
Basic Knowledge in java programming:
1.
2.
3.
4.
5.
Java is an Object-Oriented Programming (OOP) Language.
A Java program is always made up of one or more classes.
A Java class contains one or more methods, and sometime data fields.
A Java application program always contains a method called main.
Java is case-sensitive language.
Comments:
Comments are to explain the purpose of the program.

There are three forms of comments in Java.
// This comment runs to the end of the line
/*
This comment runs to the terminating symbol,
even across line breaks
*/
/** This is a javadoc comment */
Identifiers:
1. An identifier is the name of a variable, or other item (class, method, object) you might define
in a program.
2. A Java identifier cannot begin with a digit.
3. It must only contain letters, digits or the underscore symbol.
4. Java keywords or reserved words cannot be used as identifiers.
Primitive Data Types:
There are eight primitive data types in Java:
byte
short
int
long
float
double
char
boolean
Type
integer
integer
integer
integer
floating-point number
floating-point number
single character
ture or false
Size
1 byte (8 bits)
2 bytes (16 bits)
4 bytes (32 bits)
8 bytes (64 bits)
4 bytes (32 bits)
8 bytes (64 bits)
2 bytes (16 bits)
Not applicable
String:
String is not a primitive data type in Java. A string "Hello World" is not just a list of char s. It is an
object !.
String message = "Hi!";
It is equivalent to:
Char data[] = {'H','i', '!'};
String message = new String(data);
OR:
String message = new String("Hi!");

To print a string
System.out.println(message);
String Concatenation:
You can use the + operator to join two strings as a longer string.
String name = "norah";
String message = "Hello " + name + "!";
System.out.println(message); //Hello norah!

Every string is an String object which contains a large number of methods. You can
the string methods to perform on the string:
System.out.println(message.length());//12 - length of the string
System.out.println(message.toUpperCase());// HELLO NORAH! - convert to uppercase
System.out.println(message.substring(2));//llo norah! - truncate the string
System.out.println(message.charAt(1));//e - get the second char of the string
}}
First Program :
1 // Text-printing program.
2
3
4
5
6
7
8
9
public class Welcome1
{
// main method begins execution of Java application
public static void main( String args[] )
{
System.out.println( "Welcome to Java Programming!" );
} // end method main
} // end class Welcome1
Welcome to Java Programming!
Q1) What is the output produced by the following lines of program code?
1. char a, b; a = 'b';
System.out.println(a);
b = 'c';
System.out.println(b);
a = b;
System.out.println(a);
2. public static void main(String[] args)
{ int a,b,I,j;
I=j=5;
A=i++*3;
B=++j*3;
System.out.println("a="+a+"\n"+"b="+b);
}
Q2) Write an application to calculate the equation
(Nota that: the user will enter the value of a, b, and c) .

Also, make this application in separate files
Q3) Write an application that inputs three integers from the user and displays The
average, smallest, and largest of the numbers.
LAB 3
Name:
Grade:
Object:



To print words using slash characters
To use tabs (like: \t \n \" ) in printing statements.
To use concatenation
Activities:
1. A Table of Student Grades
Write a Java program that prints a table with a list of at least 5 students together with
their grades earned (lab points, bonus points, and the total) in the format below.
///////////////////\\\\\\\\\\\\\\\\\\\
==
Student Points
==
\\\\\\\\\\\\\\\\\\\///////////////////
Name
Lab
Bonus
Total
-------------Ali
43
7
50
Mona
88
5
93
Waladeen
32
10
42
Questions:
1. What is the output of the following program?
public class a1
{
public static void main(String[] args)
{ System.out.println("This program is to print variables");
System.out.println();
System.out.println("This program \nis to print\" variables\"");
//----------------------------------------------------------------int x=5, y=8;
double z=11;
System.out.print("x= "+x+"\t\ty="+y+"\nz="+z);
y=x+20; System.out.println("y="+y);
}
}
2. Write a java application that determine a prime numbers between 1 - to any
number selected by user.(use separate files)
3. Write a program by using loop that print the following output:
54321
5432
543
54
5
Lab 4
Name: (print)
Grade:
_
Pre-Lab Questions:
1.
2.
3.
When storing data, there are many different data types to choose. What type would be best to store an age? A temperature?
The result of a calculation that needs very precise accuracy?
What is wrong with the following expression (assume all variables have been properly declared)?
a. net = ((gross – expenses) / 4) % 6) / 2
The Scanner class can be used to parse data from several different sources. When interactively reading data from the user,
what source is used and what type of object is it?
Activities:
A Table of Student Grades
Write a Java program that prints a table with a list of at least 5 students together with their grades earned (lab points, bonus points, and
the total) in the format below.
///////////////////\\\\\\\\\\\\\\\\\\\
==
Student Points
==
\\\\\\\\\\\\\\\\\\\///////////////////
Name
---Joe
William
Mary Sue
Lab
--43
50
39
Bonus
----7
8
10
Total
----50
58
49
The requirements for the program are as follows:
1.
2.
3.
Print the border on the top as illustrated (using the slash and backslash characters).
Use tab characters to get your columns aligned and you must use the + operator both for addition and string concatenation.
Make up your own student names and points—the ones shown are just for illustration purposes. You need 5 names.
Alice and Bob Age Problem
Alice and Bob are siblings. In two years, Alice will be four years younger than three time’s Bob’s current age. Fill in the b lanks of the
following code to find Alice’s current age based on Bob’s current age.
public static void main(String args[])
{
int aliceAge = 0;
int bobAge = 0;
Scanner scan = new Scanner(
);
System.out.print("What is Bob's current age? ");
bobAge = scan.
;
aliceAge =
;
System.out.println("If Bob is " + bobAge + " then Alice must be " + aliceAge +
".");
}
Sample Output
What is Bob's current age? 10
If Bob is 10 then Alice must be 24.
Computing Averages
The following program reads three integers and prints the average. Fill in the blanks so that it will work correctly.
// *******************************************************************
//
Average.java
//
//
Read three integers from the user and print their average
// *******************************************************************
import java.util.Scanner;
public class Average
{
public static void main(String[] args)
{
int val1, val2, val3;
double average;
Scanner scan = new Scanner(System.in) ;
// get three values from user
System.out.println("Please enter three integers and " +
"I will compute their average");
//compute the average
//print the average
}
}
Sample Output
Please enter three integers and I will compute their average.
Enter the first value: 5
Enter the second value: 2
Enter the third value: 7
The average is 4.666666666666667.
Lab 5
Name: (print)
Grade:
_
Pre-Lab Questions
1. Fill in the following truth table:
A
B
A && B
A || B
!(A && B)
!(A || B)
True
True
True
False
False
True
False
False
2. Use the conditional operator to write one line of source code equivalent to the following:
if(distance < 1000)
transitType = “car”;
else
transitType = “plane”;
3. What is the output of the following?
int count = 0;
int numItems = 4;
while(count < 100);
{
numItems++;
System.out.println(numItems);
count++;
}
!A && !B
!A || !B
Activities:
Computing A Raise
File Salary.java contains most of a program that takes as input an employee's salary and a rating of the employee's performance and
computes the raise for the employee. The performance rating here is being entered as a String—the three possible ratings are
"Excellent", "Good", and "Poor". An employee who is rated excellent will receive a 6% raise, one rated good will receive a 4% raise,
and one rated poor will receive a 1.5% raise.
Add the if... else... statements to program Salary to make it run as described above. Note that you will have to use the equals method
of the String class (not the relational operator ==) to compare two strings.
// ***************************************************************
//
Salary.java
//
//
Computes the amount of a raise and the new
//
salary for an employee. The current salary
//
and a performance rating (a String: "Excellent",
//
"Good" or "Poor") are input.
// ***************************************************************
import java.util.Scanner;
import java.text.NumberFormat;
public class Salary
{
public static void main (String[] args)
{
double
double
double
String
currentSalary;
raise;
newSalary;
rating;
//
//
//
//
employee's current salary
amount of the raise
new salary for the employee
performance rating
Scanner scan = new Scanner(System.in);
System.out.print ("Enter the current salary: ");
currentSalary = scan.nextDouble();
System.out.print ("Enter the performance rating (Excellent, Good, or Poor): ");
rating = scan.next();
// Compute the raise using if ...
newSalary = currentSalary + raise;
// Print the results
NumberFormat money = NumberFormat.getCurrencyInstance();
System.out.println();
System.out.println("Current Salary:
" + money.format(currentSalary));
System.out.println("Amount of your raise: " + money.format(raise));
System.out.println("Your new salary:
" + money.format(newSalary));
System.out.println();
}
}
Sample Output:
Enter the current salary: 53187.54
Enter the performance rating (Excellent, Good, or Poor): Excellent
Current Salary:
$53,187.54
Amount of your raise: $3,191.25
Your new salary:
$56,378.79
Rock, Paper, Scissors
Program Rock.java contains a skeleton for the game Rock, Paper, Scissors. Add statements to the program as indicated by the
comments so that the program asks the user to enter a play, generates a random play for the computer, compares them and annou nces
the winner (and why).
Note that the user should be able to enter either upper or lower case r, p, and s. The user's play is stored as a string to make it easy to
convert whatever is entered to upper case. Use a switch statement to convert the randomly generated integer for the computer's play to
a string.
// ****************************************************************
//
Rock.java
//
//
Play Rock, Paper, Scissors with the user
//
// ****************************************************************
import java.util.Scanner;
import java.util.Random;
public class Rock
{
public static void main(String[] args)
{
String personPlay;
//User's play -- "R", "P", or "S"
String computerPlay; //Computer's play -- "R", "P", or "S"
int computerInt;
//Randomly generated number used to determine
//computer's play
Scanner scan = new Scanner(System.in);
Random generator = new Random();
//Get player's play -- note that this is stored as a string
//Make player's play uppercase for ease of comparison
//Generate computer's play (0,1,2)
//Translate computer's randomly generated play to string
switch (computerInt)
{
}
//Print computer's play
//See who won. Use nested ifs instead of &&.
if (personPlay.equals(computerPlay))
System.out.println("It's a tie!");
else if (personPlay.equals("R"))
if (computerPlay.equals("S"))
System.out.println("Rock crushes scissors.
else
//...
}
}
Fill in rest of code
You win!!");
Counting and Summing
The following program opens a file called input.txt and sums all of the numbers in it along with counting the number of numbers. Fill
in the condition and body of the while loop so it functions correctly.The condition should use one of the Scanner iterators.
// ***************************************************************
//
CountingAndSumming.java
//
//
Reads a series of numbers from a text file and calculates
//
the sum while keeping track of the number of numbers in the
//
file.
// ***************************************************************
import java.util.Scanner;
import java.io.*;
public class CountingAndSumming
{
public static void main(String[] args) throws IOException
{
String fileName = "input.txt";
Scanner fileScan = new Scanner(new File(fileName));
int sum = 0;
int count = 0;
while(
{
)
}
System.out.println("There were " + count + " numbers in " + fileName + " and their
sum was " + sum + ".");
}
}
String Reverser
Write a small program that prompts the user for a sentence and then outputs the same sentence with the characters in each word
reversed. For example, if the user enters “This is a sample sentence.” then the output would be “sihT si a elpmas .ecnetnes.” Note the
use of multiple Scanner objects in Listing 4.9 of the text. A similar technique may be helpful with this program.
Factors
Write a program that checks a range of number a – b and determines if any of them are a factor of another number n. Have the user
enter a, b, and n, and then use a for loop to check each number between a and b.
Lab 6
Name: (print)
Grade:
_
Pre-Lab Questions
1. When might private methods be used in a class?
2.
3.
What does a toString method return if it has not been overridden?
Consider the following constructor definition:
public MyClass(String name, int ID, int year)
{
name = name;
ID = ID;
year = year;
}
If name, ID, and year are instance variables of the class, is this definition legal? Come up with two different ways of writing
this to make it both legal and more comprehensible.
Activities:
Band Booster Class
In this exercise, you will write a class that models a band booster and use your class to update sales of band candy.
1.
Write the BandBooster class assuming a band booster object is described by two pieces of instance data: name (a String) and
boxesSold (an integer that represents the number of boxes of band candy the booster has sold in the band fundraiser). The class
should have the following methods:
a. A constructor that has one parameter—a String containing the name of the band booster. The constructor should set
boxesSold to 0.
b. A method getName that returns the name of the band booster (it has no parameters).
c. A method updateSales that takes a single integer parameter representing the number of additional boxes of candy sold.
The method should add this number to boxesSold.
d. A toString method that returns a string containing the name of the band booster and the number of boxes of candy sold in
a format similar to the following:
Joe:
16 boxes
2. Write a program that uses BandBooster objects to track the sales of 2 band boosters over 3 weeks. Your program should do the
following:
a. Read in the names of the two band boosters and construct an object for each.
b. Prompt for and read in the number of boxes sold by each booster for each of the three weeks. Your prompts should include
the booster's name as stored in the BandBooster object. For example,
i. Enter the number of boxes sold by Joe this week:
c.
d.
For each member, after reading in the weekly sales, invoke the updateSales method to update the total sales by that member.
After reading the data, print the name and total sales for each member (you will implicitly use the toString method here).
Students
Write the Student class that is briefly described in Section 5.1 and Figure 5.1. All of its attributes are Strings except for the GPA,
which is a double. In addition to the operations listed in Figure 5.1, implement accessor methods for all of the instance var iables. To
calculate the GPA, generate a random float between .5 and 4.0. Also be sure to include a toString(). Write two constructors. The first
takes a name, address, and major and calls computeGPA to set the GPA. The second constructor only takes a name and add ress and
sets the major to “undeclared”. It should also call computeGPA to set the GPA.
Once you have completed writing the class, write a short driver program that creates a few students and exercises the various class
methods.
Credit Cards
In this exercise, you will write a class to represent a credit card. The class details are as follows:
1. Static Variables
a. baseRate – The minimum interest rate that the card can have. This should be a constant that is hard coded.
b. lastAccountNumber – The last account number assigned to a customer. Account numbers should be assigned
sequentially.
2. Instance Variables
a. accountholder – The name of the person who owns the card.
b. accountNumber – A unique 7-digit identifier number.
c. creditScore – The account holder’s credit score.
d. rate – The annual interest rate charged to the card.
e. balance – The current balance on the card.
f. creditLimit – The card holder’s credit limit.
3. Methods
a. Constructor – Should only take the account holder’s name and a credit score. The next account number available
should be assigned. The balance will be 0 as nothing has been charged yet. The rate and credit limit will be
determined by the credit score. Use the following table to set the rate and credit limit.
Credit Score
0-300
300-500
500-700
700+
Rate
baseRate + 10%
baseRate + 7%
baseRate + 4%
baseRate + 1%
b.
c.
d.
e.
f.
g.
Limit
$1000
$3000
$7000
$15000
makePurchase – Takes a purchase amount as a parameter and updates the current balance. If the amount + balance >
creditLimit, deny the transaction.
makePayment – Takes a payment amount as a parameter and updates the current balance. If the payment is greater
than the balance, set the balance to zero and print an appropriate message. If the payment is less than 10% of the
balance, apply the payment and raise the account holder’s rate by 1%. If the balance is paid off entirely, raise the
creditScore by 10. If the increased creditScore changes where the account holder falls in the above table, change the
rate and limit as appropriate.
raiseRate – Raises the account holder’s rate by a given percentage.
raiseLimit – Raises the account holder’s limit by a given dollar amount.
calculateBalance – Calculates the balance on a monthly basis. Remember that the rate is yearly, so the formula for
calculating the balance monthly is balance + (balance * (rate / 12)).
toString – Print the account holder’s name, account number obscured with stars (ex: 1234567 would display as
****567), balance, and limit.
To test your class, write a driver program to track an account holder over six months. Each month, allow the account holder to make
as many purchases as he wishes. At the end of each month, if the balance is greater than 0, ask the user if he would like to make a
payment. Apply the payment if he makes one. If a payment is not made during any given month when there is a balance on the card,
raise
the
rate
by
2%.
Finally,
calculate
the
new
balance
at
the
end
of
each
month.
Lab 7
Name: (print)
Grade:
_
Pre-Lab Questions
1.
2.
3.
Give an example of a good use of an abstract class not mentioned in the textbook.
How many children can any parent class have? How many parents can a child class have?
How can you make sure a method is not overridden in a child class?
Activities:
Overriding Methods
Below is Person.java, a simple class that represents a person. Since it does not explicitly inherit from any other classes, it defaults
from the Object class in java.lang by default. This means it inherits all of Object’s methods, including the equals() method. However,
the equals() method in Object only returns true if both objects are actually the same object in memory, alia ses of one another. Override
the equals() method so it returns true if two different Person objects share the same instance data.
// ****************************************************************
// Person.java
//
// A class that represents a person.
//
// ****************************************************************
public class Person
{
private String firstName;
private String lastName;
private int age;
public Person (String newFirstName, String newLastName, int newAge)
{
firstName = newFirstName;
lastName = newLastName;
age = newAge;
}
public String getFirstName()
{
return firstName;
}
public String getLastName()
{
return lastName;
}
public int getAge()
{
return age;
}
}
Exploring Inheritance
File Dog.java contains a declaration for a Dog class. Save this file to your directory and study it—notice what instance variables and
methods are provided. Files Labrador.java and Yorkshire.java contain declarations for classes that extend Dog. Save and study these
files as well.
File DogTest.java contains a simple driver program that creates a dog and makes it speak. Study DogTest.java, save it to your
directory, and compile and run it to see what it does. Now modify these files as follows:
1.
Add statements in DogTest.java after you create and print the dog to create and print a Yorkshire and a Labrador. Note that t he
Labrador constructor takes two parameters: the name and color of the labrador, both strings. Don't change any files besides
DogTest.java. Now recompile DogTest.java; you should get an error saying something like
./Labrador.java:18: Dog(java.lang.String) in Dog cannot be applied to ()
{
^
1 error
If you look at line 18 of Labrador.java it's just a {, and the constructor the compiler can't find (Dog()) isn't called anywhere in this
file.
a. What's going on? (Hint: What call must be made in the constructor of a subclass?)
=>
b.
2.
Fix the problem (which really is in Labrador) so that DogTest.java creates and makes the Dog, Labrador, and Yorkshire all
speak.
Add code to DogTest.java to print the average breed weight for both your Labrador and your Yorkshire. Use the
avgBreedWeight() method for both. What error do you get? Why?
=>
Fix the problem by adding the needed code to the Yorkshire class.
3.
Add an abstract int avgBreedWeight() method to the Dog class. Remember that this means that the word abstract appears in the
method header after public, and that the method does not have a body (just a semicolon after the parameter list). It makes sense
for this to be abstract, since Dog has no idea what breed it is. Now any subclass of Dog must have an avgBreedWeight method;
since both Yorkshire and Laborador do, you should be all set.
Save these changes and recompile DogTest.java. You should get an error in Dog.java (unless you made more changes than
described above). Figure out what's wrong and fix this error, then recompile DogTest.java. You should get another error, this time
in DogTest.java. Read the error message carefully; it tells you exactly what the problem is. Fix this by changing DogTest (wh ich
will mean taking some things out).
// ****************************************************************
// Dog.java
//
// A class that holds a dog's name and can make it speak.
//
// ****************************************************************
public class Dog
{
protected String name;
// -----------------------------------------------------------// Constructor -- store name
// -----------------------------------------------------------public Dog(String name)
{
this.name = name;
}
// -----------------------------------------------------------// Returns the dog's name
// -----------------------------------------------------------public String getName()
{
return name;
}
// -----------------------------------------------------------// Returns a string with the dog's comments
// -----------------------------------------------------------public String speak()
{
return "Woof";
}
}
//
//
//
//
//
//
//
//
****************************************************************
Labrador.java
A class derived from Dog that holds information about
a labrador retriever. Overrides Dog speak method and includes
information about avg weight for this breed.
****************************************************************
public class Labrador extends Dog
{
private String color; //black, yellow, or chocolate?
private static int breedWeight = 75;
public Labrador(String name,
{
this.color = color;
}
String color)
// -----------------------------------------------------------// Big bark -- overrides speak method in Dog
// -----------------------------------------------------------public String speak()
{
return "WOOF";
}
// -----------------------------------------------------------// Returns weight
// -----------------------------------------------------------public static int avgBreedWeight()
{
return breedWeight;
}
}
//
//
//
//
//
//
//
****************************************************************
Yorkshire.java
A class derived from Dog that holds information about
a Yorkshire terrier. Overrides Dog speak method.
****************************************************************
public class Yorkshire extends Dog
{
public Yorkshire(String name)
{
super(name);
}
// -----------------------------------------------------------// Small bark -- overrides speak method in Dog
// -----------------------------------------------------------public String speak()
{
return "woof";
}
}
//
//
//
//
//
//
****************************************************************
DogTest.java
A simple test class that creates a Dog and makes it speak.
****************************************************************
public class DogTest
{
public static void main(String[] args)
{
Dog dog = new Dog("Spike");
System.out.println(dog.getName() + " says " + dog.speak());
}
}
Bank Accounts
Design and write 3 classes – Account, CheckingAccount, and SavingsAccount. Have CheckingAccount and SavingsAccount inherit
from Account. In Account, you should include an account number, an account balance, a deposit and toString method, and an abs tract
withdraw method. Since deposits work the same way in both child classes, make sure they cannot override it. The constructor should
only take an initial deposit and generate a random 5 digit account number. The toString should display the account number and the
balance. Use a NumberFormat object to format the balance.
In the CheckingAccount class add a minimum balance and overdraft fee. Implement the withdraw method so that overdrafts are
allowed, but the overdraft fee is incurred if the balance drops below the minimum balance. Override the toString method to di splay
everything the Account toString displays plus the minimum balance. Use the parent class toString to do most of the work. You should
not need a NumberFormat object in this method.
In the SavingsAccount class add an annual interest rate and a method to recalculate the balance every month. Since the intere st rate is
annual, make sure to calculate the interest accordingly. Override the toString method to display everything the Account toStr ing
displays plus the interest rate. Like the CheckingAccount toString, you should use the parent class to do most of the work a nd should
not need a NumberFormat object.
Create a driver class to instantiate and exercise each of the account types.
Resources:

The Java API documentation is located at: http://java.sun.com/javase/6/docs/api/
Lab 8
Name: (print)
Grade:
Description of chapter 8
8.1 Class Definitions
Instance Variables and Methods
More about Methods
Local Variables
Blocks
Parameters of a Primitive Type
Simple Cases with Class Parameters
The this Parameter
Methods that Return a Boolean Value
The Methods equals and toString
Recursive Methods
8.2 Information Hiding and Encapsulation
public and private Modifiers
Accessor and Mutator Methods
Preconditions and Postconditions
8.3 Overloading
Rules for Overloading
8.4 Constructors
Constructor Definitions
Default Variable Initializations
An Alternative Way to Initialize Instance Variables
The StringTokenizer Class
_
Chapter 7, Chapter 8: Defining Classes I, II
Lab 8 objectives
The aims of this lab are:
- Use different modifiers for the instance variables (public, private, …),
- Declare and use accessor and mutator methods,
- Declare and use of equals and toString methods,
- Declare overloaded constructors.
Preparatory work
a) Open JCreator Software.
b) Create a project named lab8 and save it in D:\IS224\Labs\.
Exercise 1
1. Create a new Java file named exercise1 and add it to the lab9 project.
2. Create a class named Circle that contains:
a. A double variable named radius,
b. A double constant named pi and equals 3.14,
c. A constructor with one argument to initialize the variable radius.
d. A method named CircleArea with one parameter (the radius) to compute and then
return the area of the circle ( = pi * radius * radius ).
e. A method named CirclePerimeter with one parameter (the radius) to compute and
then return the perimeter of the circle ( = 2* pi * radius ).
3. Write a main class named CircleTest that:
a. Instantiates the Circle class with an object named c with radius = 2.3.
b. Displays the area and the perimeter of the circle c.
Exercise 2
1. Create a new Java file named exercise2 and add it to the lab8 project.
2. Create a class to represent a Flight class. A Flight has a flight number, a source, a
destination, and a number of available seats. The class should have:
a. A constructor to initialize the four instance variables.
b. An overloaded constructor to initialize the flight number and the number of
available seats instance variables only. (Note: Initialize the source and the
destination
instance
variables
to
empty
strings).
c. An overloaded constructor to initialize the flight number instance variable only.
(Note: Initialize the source and the destination instance variables to empty strings;
and the number of available seats to zero).
d. One accessor method for each one of the four instance variables.
e. One mutator method for each one of the four instance variables except the flight
number.
f. A method public void reserve (int numberOfSeats) to reserve seats on the
flight. You have to check that there are sufficient seats available.
g. A method public void cancel (int numberOfSeats) to cancel one or more
reservations.
h. A toString method to easily return the flight information as follows:
Flight No: 1234
From: Dammam To:
Riyadth Available
Seats: 18
i. An equals method to compare two flights (Two flights are considered to be equal
if they have the same flight number).
3. Create a main class to test the methods declared in the Flight class.
Exercise1 Solution
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package exercise1;
public class Circle {
private double r;
private double p = 3.14;
public Circle(double s){
s = r;
}
public double circleArea(double r){
return(p * r* r);
}
public double circleParameter(double r){
return(p * 2 * r);
}
----------------------------------------------------------------------------package exercise1;
public class CircleTest {
public static void main(String[] args) {
Circle c = new Circle(2.3);
System.out.printf("the area = %f\n the perimter = %f\n", c.circleArea(2.3) ,
c.circleParameter(2.3));
}
}
----------------------------------------------------------------------------------Exercise2 Solution
package exercise2;
public class CircleTest {
public static void main(String[] args) {
Flight c = new Flight(123, 34, "Dammam" , "Riyadh");
Flight s = new Flight(123, 34, "Dammam" , "Riyadh");
Flight w = new Flight(124, 24, "Qassim" , "Riyadh");
System.out.printf("%s%n" , c);
c.reserve(20);
System.out.printf("%s%n" , c);
c.cancel(6);
System.out.printf("%s%n" , c);
System.out.printf("%s%n", c.equal(s));
System.out.printf("%s%n", c.equal(w));
System.out.printf("%s%n" , w);
} }
----------------------------------------------------------------------------package exercise2;
public class Flight{
private int fn;
private String des;
private String src;
private int av;
public Flight(int x , int y , String s , String d){
fn = x ;
av = y ;
src = s;
des = d;
}
public Flight(int x , int y){
fn = x ;
av = y ;
src = "";
des = "";
}
public Flight(int x){
fn = x ;
av = 0 ;
src = "";
des = "";
}
public int getFn(){
return fn;
}
public int getAv(){
return av;
}
public String getDes(){
return des;
}
public String getSrc(){
return src;
}
public void setAv(int x){
av = x;
}
public void setDes(String x){
des = x;
}public void setSrc(String x){
src = x;
}
public void reserve(int x){
if(x <= av) {av = av-x;}
}
public void cancel(int x){
av = av + x;
}
public String toString(){
String x = "";
x = x + "Flight NO : " + fn + "\n";
x = x + "From : " + src + "\n";
x = x + "to : " + des + "\n";
x = x + "Available seats : " + av + "\n";
return x;
}
public String equal( Flight b){
if(fn == b.fn) return "equal \n";
else return "not equal\n";
}
}