Download Lab5-cpcs-203

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
KING ABDULAZIZ UNIVERSITY
Faculty of Computing & Information Technology
Department of Computer Science
Lab Manual
CPCS203
Programming II
(Object-oriented)
1432/1433H
Lab - 5
Learning Procedure
1)
Stage J (Journey inside-out the concept)
2)
Stage a1 (apply the learned)
3)
Stage v (verify the accuracy)
4)
Stage a2 (assess your work)
Term I
2011
Lab-5: Selection Statements
Laboratory 5:
Statement Purpose:
This lab will teach you how practically use Selection Statements in java.
Objective:
This lab teaches you the following topics:








Implement a selection control using if statements
Implement a selection control using switch statements
Write boolean expressions using relational and boolean expressions
Evaluate given boolean expressions correctly
Nest an if statement inside another if statement
Writing two classes.
Describe how objects are compared
Choose the appropriate selection control statement for a given task
Instructor Note:
As pre-lab activity, read Chapter 5 from the book (An Introduction to ObjectOriented Programming with Java, 4th Edition by C. THOMAS WU (Book’s
website www.mhhe.com/wu), and also as given by your theory instructor.
Names
I.D.
1. .……………..……………………………….
………………………………
2. ..……………………………………………..
………………………………
3. .……………………………………………...
………………………………
4. .……………………………………………..
..…………………………….
CPCS203 – The Lab Note
Lab-5
1
Term I
2011
Lab-5: Selection Statements
1) Stage J (Journey)
Selection Statements
Decisions, decisions, decisions. From the moment we are awake until the time
we go to sleep, we are making decisions. Should I eat cereal or toast? What
should I wear to school today? Should I eat at the cafeteria today? And so
forth. We make many of these decisions by evaluating some criteria. If the
number of students in line for registration seems long, then come back
tomorrow for another try. If today is Monday, Wednesday, or Friday, then eat
lunch at the cafeteria.
Computer programs are no different. Any practical computer program contains
many statements that make decisions. Often a course of action is determined
by evaluating some kind of a test (e.g., Is the remaining balance of a meal card
below the minimum?). Statements in programs are executed in sequence,
which is called sequential execution or sequential control flow. However, we
can add decision-making statements to a program to alter this control flow. For
example, we can add a statement that causes a portion of a program to be
skipped if an input value is greater than 100. Or we can add a statement to
disallow the purchase of food items if the balance of a meal card goes below a
certain minimum. The statement that alters the control flow is called a control
statement. In this chapter we describe some important control statements,
called selection statements.
2) Stage a1 (apply)
Lab Activities:
1. Assume that x is 1, show the result of the following Boolean expressions:

(true) && (3 > 4) …………………………

!(x > 0) && (x > 0) …………………………

(x > 0) || (x < 0) …………………………

(x != 0) || (x == 0) …………………………

(x >= 0) || (x < 0) …………………………

(x != 1) == !(x == 1) …………………………
CPCS203 – The Lab Note
Lab-5
2
Term I
2011
Lab-5: Selection Statements
2. Write a Boolean expression that evaluates to true if a number stored in
variable num is between 1 and 100.
3. Following example demonstrate the concept of comparing objects.
Examine the code for the Demo class and predict the output. Now run
the program and observe your output. Draw a series of state-ofmemory diagrams to explain what happens.
/* Class OurPoint provides various routines to manipulate
points in the coordinate plane (x, y). */
(a)
Create a Java class and named it OurPoint
public class OurPoint {
(b) Declare x , y coordinate of a point
private double xCoord;
private double yCoord;
(c)
Declare default constructor
public OurPoint( ) {
xCoord = 0;
yCoord = 0;
}
(d) Declare and define class data members
//
//
//
//
//
public Methods:
void setX ( double );
void setY ( double );
double getX ( double );
double getY ( double );
/* Changes the value of the x-coordinate of a point */
public void setX (double x) {
xCoord = x;
}
/*** Changes the value of the y-coordinate of a point
* * @param y the new value for the x-coordinate of
this point
*/
public void setY (double y) {
// this is a stub
}
/* Returns the x-coordinate of a point */
public double getX () {
return xCoord;
}
/* Returns the y-coordinate of a point
*/
CPCS203 – The Lab Note
Lab-5
3
Term I
2011
Lab-5: Selection Statements
public double getY () {
// this is a stub
return yCoord; } }
(e) Create a new java main class and name it Demo.java
public class Demo {
public static void main (String [] args) {
int x, y;
x = 7;
y = 7;
if (x == y)
// comparing integers
System.out.println("The ints are equal");
else
System.out.println("The ints are NOT equal");
OurPoint p, q;
p = new OurPoint (2,3);
q = new OurPoint (2,3);
if (p == q)
// comparing Objects
System.out.println("(1)The points are equal");
else
System.out.println("(1)The points are NOT equal");
OurPoint a, b;
a = p;
b = p;
if (a == b) // comparing Objects
System.out.println("(2)The points are equal");
else
System.out.println("(2)The points are NOT equal");
}
}
(f) Write an equals() method for the OurPoint class. This should return
true if the two OurPoint objects have the same x- and ycoordinates. For example, for the code segment
p = new OurPoint (2,3);
q = new OurPoint (2,3);
if (p.equals(q))
System.out.println("(1)The points are equal");
else
System.out.println("(0)The points are NOT
equal");
CPCS203 – The Lab Note
Lab-5
4
Term I
2011
Lab-5: Selection Statements
the output should be "(1)The points are equal". Make the above
change to the Demo.java file and compile, run, and examine your
results.
4. Learn how to create classes that can be used in creating objects
4.1. Create new class called " Employee "
Create the following constructor:
a. public Employee()
b. Create the following methods:
c. public void setSalary(double employeeSalary)//to change the
Salary
d. public int getNumber() // to get the number of the Employee
e. public String getName() // to get the name of the Employee
f. public double getSalary()//to get the Salary of the Employee
g. public void deductions(double amount) //to detect the salary of
the Employee by the given amount
4.2. Create new class called "TestEmployee" to test "Employee" class.
Create new two object of “Employee " class.
Let the user input the field of the Employee object.
Detect 80.5 SR from the salary of the first employee.
Use the getter methods to print the information of employees as follows:
CP203 *** company ***
* Name: Ali
* EmpNo: 123
* Salary: 3454 SR
****** Thank you ****
CPCS203 – The Lab Note
Lab-5
5
Term I
2011
Lab-5: Selection Statements
3) Stage v (verify)
Home Activities:
1. Suppose that x is 1. What is x after the evaluation of the following
expression?
(x > 1) && (x++ > 1)
2. Write a program that order three integer’s number from smallest to
biggest. The integers are entered from the input dialogs and stored in
variables num1, num2, and num3, respectively. For example suppose
user has entered num1 = 5 , num2= 2, num3=7 respectively, your
answer must be 2, 5 ,7 [ hint: use if statements]
3. Write a program which asks the user to enter their marital status,
corresponding to a letter input. married = 'm', single = 's', divorced =
'd' , widowed = 'w'
When the user enters the letter, their corresponding status should be
printed to the screen. If the user enters anything other than m,s,d, or w
the message "Invalid Code" should be printed.
4. (Using the &&, || and ^ operators) Write a program that prompts the
user to enter an integer and determines whether it is divisible by 5 and
6, whether it is divisible by 5 or 6, and whether it is divisible by 5 or 6,
but not both. For example, if your input is 10, the output should be
Is 10 divisible by 5 and 6? false
Is 10 divisible by 5 or 6? true
Is 10 divisible by 5 or 6, but not both? true
5. Write a program called PrintWord which prints "ONE", "TWO",... ,
"NINE", "OTHER" if the int variable "number" is 1, 2,... , 9 or other,
respectively.
Use (a) a "nested-if" statement; (b) a "switch-case" statement.
6. Employees at MyJava Lo-Fat Burgers earn the basic hourly wage of
$7.25. They will receive time-and-a-half of their basic rate for overtime
hours. In addition, they will receive a commission on the sales they
generate while tending the counter. The commission is based on the
following formula:
CPCS203 – The Lab Note
Lab-5
6
Term I
2011
Lab-5: Selection Statements
Sales Values
$1.00 to $99.99
$100.00 to $299.99
>= $300.00
Commission
5 % of total sales
10 % of total sales
15 % of total sales
Write an application that inputs the number of hours worked and the
total sales and computes the wage.
7. Your history instructor gives three tests worth 50 points each. You can
drop one of the first two grades. Your final grade is the sum of the best
of the first two grades and the third grade. Given three test grades,
write a program that calculates the final letter grade using the following
cut-off points. The output should list all three test grades, state what
test was dropped and the final letter grade
>= 90 A
< 90, >= 80 B
< 80, >= 70 C
< 70, >= 60 D
< 60 F
For example, if your input is 45 15 25 (you do not need to format the
input), the output of your program should be very similar to:
First test: 45
Second test: 15
Third test: 25
After dropping test 2, the final grade is 70. The final letter grade is C.
(Extra) Work at Home:
Java Parking Application
In this section we are going to calculate the parking fare for customers who
park their cars in a parking lot. To create this application, we have used switch
case statement through which we have allowed the user to select their vehicle
type in the form of choice and then enter the number of hours they want to
keep their vehicle in the parking area. In order to calculate the fare, we have
used following information:
TWO WHEELER : $0.00/hr first 3 hr $1.50/hr after 3 hr
CAR : $1.00/hr first 2 hr $2.30/hr after 2 hr
BUS : $2.00/hr first hr $3.70/hr after 1 hr
CPCS203 – The Lab Note
Lab-5
7
Term I
2011
Lab-5: Selection Statements
Here is the code:
import java.util.*;
import java.text.*;
class Parking {
public static void main(String[] args) {
DecimalFormat df = new DecimalFormat("$##.##");
Scanner input = new Scanner(System.in);
double hr = 0.0;
int menu = 0;
System.out.println("Parking Charges");
System.out.println();
System.out.println("1. Two Wheeler");
System.out.println("2. Car");
System.out.println("3. Bus or Truck");
System.out.println("4. Exit");
System.out.print("Please enter your choice: ");
menu = input.nextInt();
System.out.println();
switch (menu) {
case 1:
System.out.print("Enter Number of hours: ");
hr = input.nextDouble();
System.out.println("**********Charges**********");
System.out.println("Vehicle type= Two Wheeler");
if (hr > 3) {
double amount = (hr - 3) * 1.50;
System.out.println("Charges= " + df.format(amount));
} else {
System.out.println("No charges");
}
break;
case 2:
System.out.print("Enter Number of hours: ");
hr = input.nextDouble();
System.out.println("**********Charges**********");
System.out.println("Vehicle type= Car");
if (hr > 2) {
double amount = (hr - 2) * 2.30 + 2.00;
System.out.println("Charges= " + df.format(amount));
} else {
double amount = (hr) * 1.00;
System.out.println("Charges= " + df.format(amount));
}
break;
case 3:
CPCS203 – The Lab Note
Lab-5
8
Term I
2011
Lab-5: Selection Statements
System.out.print("Enter Number of hours: ");
hr = input.nextDouble();
System.out.println("**********Charges**********");
System.out.println("Vehicle type= Bus/Truck");
if (hr > 1) {
double amount = (hr - 3) * 3.70 + 2.00;
System.out.println("Charges= " + df.format(amount));
} else {
double amount = (hr) * 2.00;
System.out.println("Charges= " + df.format(amount));
}
break;
case 4:
break;
default:
System.out.println("Invalid Entry!");
}
}
}
OUTPUT:
CPCS203 – The Lab Note
Lab-5
9
Term I
2011
Lab-5: Selection Statements
1) Stage a2 (assess)
Homework 5:
For this lab you are requested to solve Lab homework and to submit it before
the deadline.
Lab Homework:
The laboratory homework of this lab (and also all the following labs in this
manual) should include the following items/sections:
 A cover page with your name, course information, lab number and title,
and date of submission.
 Programming: a brief description of the process you followed in conducting
the coding of the homework solution.
 Results obtained throughout the written code followed with brief analysis
of these results.
 A zip file including both the Java project folder and the work file contains
all items/sections above.
Lab Report:
The laboratory report of this lab (and also all the following labs in this manual)
should include the following items/sections:
 A cover page with your name, course information, lab number and title,
and date of submission.
 A summary of the addressed topic and objectives of the lab.
 Implementation: a brief description of the process you followed in
conducting the implementation of the lab scenarios.
 Results obtained throughout the lab implementation, the analysis of these
results, and a comparison of these results with your expectations.
 Answers to the given exercises at the end of the lab. If an answer
incorporates new graphs, analysis of these graphs should be included here.
 A conclusion that includes what you learned, difficulties you faced, and any
suggested extensions/improvements to the lab.
Note: only a softcopy is required for both homework and report, please do not
print or submit a hard copy.
CPCS203 – The Lab Note
Lab-5
10