Download Lab

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 - 3
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-3: Handling Numerical Data
Laboratory 3:
Statement Purpose:
This lab will teach you how to deal with different form of Numerical Data and
applying various arithmetic operations.
Activity Outcomes:
This lab teaches you the following topics:
 Write arithmetic expressions in Java.
 Memory Concepts, Variables and Constants.
 Assignment Statements and Assignment Expressions.
 Select proper types for numerical data.
 Numeric Data Types and Operations and Numeric Type Conversions.
 Input / Output
 Maths Class
Instructor Note:
As pre-lab activity, read Chapter 3 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-3
1
Term I
2011
Lab-3: Handling Numerical Data
1) Stage J (Journey)
Introduction
This lab is designed to give you practice with some of the basics in Java. We will
continue ideas from lab 1 by correcting logic errors while looking at
mathematical formulas in Java. We will explore the difference between integer
division and division on your calculator as well as reviewing the order of
operations. This lab also introduces communicating with the user. How console
input and output work, we will now need to learn how to program user input,
by investigating the lines of code that we need to add in order to use the
Scanner class. We will also learn the method call needed for output.
We will bring everything we have learned together by creating a program from
an algorithm. Finally, you will document the program by adding comments.
Comments are not read by the computer, they are for use by the programmer.
They are to help a programmer document what the program does and how it
accomplishes it. This is very important when a programmer needs to modify
code that is written by another person.
The Math class
contains the methods needed to perform basic mathematical functions.
public static double sin(double radians)
public static double cos(double radians)
public static double tan(double radians)
public static double asin(double radians)
public static double acos(double radians)
public static double atan(double radians)
public static double toRadians(double degree)
public static double toDegrees(double radians)
public static double exp(double x)
public static double log(double x)
public static double log10(double x)
CPCS203 – The Lab Note
Lab-3
2
Term I
2011
Lab-3: Handling Numerical Data
public static double pow(double x, double b)
public static double sqrt(double x)
For example:
Math.sin(0) returns 0.0 , Math.cos(0) returns 1.0
,
Math.exp(1) returns 2.71828 , Math.log(Math.E) returns 1.0 ,
Math.log10(10) returns 1.0
, Math.pow(2, 3) returns 8.0 ,
Math.pow(3, 2) returns 9.0 ,
Math.pow(3.5, 2.5) returns
22.91765 , Math.sqrt(4) returns 2.0 , Math.sqrt(10.5) returns
3.24
Example:
Some simple Trigonometry:
A. File -> New ->Java Main Class-> named it SimpleTrig
B. Write Code inside the main method and test it by running the
application.
import javax.swing.*;
public class SimpleTrig {
public static void main (String [] args)
{
String angleStr;
double angle, angleCosine, angleSine, angletan;
angleStr = JOptionPane.showInputDialog(null, "Enter an angle
(in degrees)");
angle = Double.parseDouble(angleStr);
angleCosine = Math.cos(angle);
JOptionPane.showMessageDialog(null, "The cosine of " + angle
+ " degrees is " + angleCosine);
angleSine = Math.sin(angle);
JOptionPane.showMessageDialog(null, "The sine of " + angle +
" degrees is " + angleSine );
angletan = Math.tan(angle);
JOptionPane.showMessageDialog(null, "The tan of " + angle + "
degrees is " + angletan);
}
}
CPCS203 – The Lab Note
Lab-3
3
Term I
2011
Lab-3: Handling Numerical Data
2) Stage a1 (apply)
Activity 1:
A program explains the concepts of objects in OOP:
A. File -> New ->Java Main Class-> and named it Customer
B. Copy the Code inside the class and test it by running the application
//Example 1: Customer.java
import javax.swing.*;
public class Customer {
String name;
// methods, Update customer name
public void changeName( String
n)
{
name = n;
}
// Get customer name
public String getName()
{
return name;
}
public static void main(String[] args)
{
// TODO code application logic here
Customer c1 =new Customer();
Customer c2 =new Customer();
c1.changeName("Karen");
JOptionPane.showMessageDialog(null, "Customer c1's name is " +
c1.getName() +"\n");
JOptionPane.showMessageDialog(null, "Customer c2's name is "
+ c2.getName() + "\n");
}
}
Prepare the answers to these questions:
A. Do the Customer object variables c1 and c2 refer to the same Customer
or to different ones?
B. What does the state-of-memory diagram look like when the output is
generated?
CPCS203 – The Lab Note
Lab-3
4
Term I
2011
Lab-3: Handling Numerical Data
Activity 2:
Change the above code and try to answer the expected output of the
program
//Example 2: Customer.java
import javax.swing.*;
public class Customer
{
String name;
// methods , Update customer name
public void changeName( String n)
{
name = n;
}
// Get customer name
public String getName()
{
return name;
}
public static void main (String [] args){
Customer c1 = new Customer();
Customer c2 = c1;
c1.changeName("Karen");
JOptionPane.showMessageDialog(null,
"Customer c1's name is
" + c1.getName());
JOptionPane.showMessageDialog(null,
"Customer c2's name is
" + c2.getName());
}
}
Examine the code and predict the results of running this program.
After predicting the outcome, compile and run it.
Prepare answers to these questions:
A. Do Customer variables c1 and c2 refer to the same Customer object or
different objects?
B. What does the state-of-memory diagram look like when the output is
generated? (Draw a picture of it.)
C. Try the following code and find the difference between the two cases
Example2 and Example3.
import javax.swing.*;
public class Variables3 {
CPCS203 – The Lab Note
Lab-3
5
Term I
2011
Lab-3: Handling Numerical Data
public static void main(String[] args) {
int i1 = 5;
int i2 = i1;
i1 = 7;
JOptionPane.showMessageDialog(null, "integer i1's value is " +
i1);
JOptionPane.showMessageDialog(null, "integer i2's value is " + i2);
}
}
Activity 3
write a java application to interchange values of two variables with a use of
3rd variable.
A. File -> New ->Java Main Class-> and named it JavaSwap
B. Write Code inside the main method and test it by running the
application.
Activity 4
Write a program that obtains minutes and remaining seconds from an
amount of time in seconds. For example, 500 seconds contains 8 minutes and
20 seconds.
Output of the program:
A. File -> New ->Java Main Class-> and named it JavaSecond2Minutes
B. Write your Code inside the method main() and test it by running the
application.
CPCS203 – The Lab Note
Lab-3
6
Term I
2011
Lab-3: Handling Numerical Data
Activity 5
Arithmetic Expressions:
Writing numeric expressions in Java involves a straightforward translation of
an arithmetic expression using Java operators. For example, the arithmetic
expression
Can be translated into a Java expression as:
(3 + 4 * x) / 5 – 10 * (y - 5) * (a + b + c) / x + 9 * (4 / x + (9 + x) / y)
Exercise: translate the following expressions in Java. For any value of a , x , b ,
c , p , r, q , w , y
1. y = ax3 + ax2 + bx + c
2.
Activities 6
Input / Output:
Using System.out to display the result to the console:
1. System.out.print( "Welcome to " );
2. System.out.println( "Java Programming!" );
3. System.out.println( "Welcome\nto\nJava\nProgramming!" );
4. System.out.printf( "%s\n%s\n", "Welcome to", "Java Programming!"
);
Reading Data from the keyboard using Scanner Class
Step 1 : import java.util.Scanner;
Step 2: create Scanner to obtain input from command window
Scanner input = new Scanner( System.in );
object of Scanner Class
CPCS203 – The Lab Note
Lab-3
// input is the
7
Term I
2011
Lab-3: Handling Numerical Data
Step 3: input.nextInt(); // read number
Activity 6.1
let's look at a simple program that computes the area of a circle.
A. File -> New ->Java Main Class-> named it ComputeCircleArea
B. Write Code inside the main method and test it by running the
application.
The program can be expanded as follows:
// Example
a simple program that computes the area of a
circle.
// Step 1 : import java.util.Scanner;
import java.util.Scanner;
public class ComputeCircleArea {
static final double PI =3.1414;
public static void main(String[] args) {
double radius, area;
Scanner
in = new Scanner (System.in);
System.out.println("Enter Raduis");
// Step 2: Read in radius
radius = in.nextDouble();
// Step 3: Compute area
area=PI*radius*radius;
// Step 4: Display the area
System.out.println("Area of Circle\t"+ area);
} }
CPCS203 – The Lab Note
Lab-3
8
Term I
2011
Lab-3: Handling Numerical Data
Activity 6.2
Using the Scanner Class for User Input:
1. Add an import statement above the class declaration to make
the Scanner class available to your program.
2. In the main method, create a Scanner object and connect it to
the System.in object.
3. Prompt the user to enter his first name.
4. Read the name from the keyboard using the nextLine method,
and store it into a variable called firstName (you will need to
declare any variables you use).
5. Prompt the user to enter his last name.
6. Read the name from the keyboard and store it in a variable called
lastName.
7. Concatenate the firstName and lastName with a space between them and
store the result in a variable called fullName.
8. Print out the fullName.
9. Compile, debug, and run, using your name as test data.
10.Since we are adding on to the same program, each time we run the
program we will get the output from the previous tasks before the output
of the current task.
CPCS203 – The Lab Note
Lab-3
9
Term I
2011
Lab-3: Handling Numerical Data
3) Stage v (verify)
Home Exercises:
1. Write an application that inputs one number consisting of five digits
from the user, separates the number into its individual digits and prints
the digits separated from one another by three spaces each.
For example, if the user types in the number 42339, the program should
print 4 2 3 3 9 .
[Hint: You will need to use both division and remainder operations to
"pick off" each digit.]
2. Assume that int a = 1 and double d = 1.0, and that each expression
is independent. What are the results of the following expressions?
i.
a = 46 / 9;
ii.
a = 46 % 9 + 4 * 4 - 2;
iii.
a = 45 + 43 % 5 * (23 * 3 % 2);
iv.
a % = 3 / a + 3;
v.
d
vi.
d + = 1.5 * 3 + (++a);
vii.
d - = 1.5 * 3 + a++;
= 4 + d * d + 4;
3. Write an application that inputs one number consisting of five digits
from the user, and prints the digits in reverse order. For example, if the
user types in the number 42339, the program should print 93324.
4. Write a program in Java to interchange values of two variables without
using the third variable. If A=10 , B=20 after interchange A=20, B=10
5. Write a program that reads an integer between 0 and 1000 and adds all
the digits in the integer. For example, if an integer is 932, the sum of all
its digits is 14.
CPCS203 – The Lab Note
Lab-3
10
Term I
2011
Lab-3: Handling Numerical Data
6. Write a program to evaluate the following method calls:
A.
Math.sqrt(4)
B.
Math.sin(2 * Math.PI)
C.
Math.cos(2 * Math.PI)
D.
Math.pow(2, 2)
E.
Math.log(Math.E)
F.
Math.exp(1)
G.
Math.max(2, Math.min(3, 4))
H.
Math.rint(-2.5)
I.
Math.ceil(-2.5)
J.
Math.floor(-2.5)
K.
Math.round(-2.5f)
L.
Math.round(-2.5)
M.
Math.rint(2.5)
N.
Math.ceil(2.5)
O.
Math.floor(2.5)
P.
Math.round(2.5f)
Q.
Math.round(2.5)
R.
Math.round(Math.abs(-2.5))
CPCS203 – The Lab Note
Lab-3
11
Term I
2011
Lab-3: Handling Numerical Data
1) Stage a2 (assess)
Homework 3:
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-3
12