Anda di halaman 1dari 46

DATA STRUCTURES

USING JAVA

PROGRAMMING DEPARTMENT

November 2010

Programming NC IV
Information and Communications Technology

Compiled by:

EUGENE F. GALANG
Area Chair

Reviewed by: Approved by:

ANTONIO M. ERRO CONRADO T. CAMIGLA


Dean, Academic Affairs School Director

No part of this module may be reproduced or utilized in any form or by any means (electronic,
photocopying, and recording) without the written permission of the author and the school.
2
TABLE OF CONTENTS
D
Introduction to Java 4 R
Two main deployment environments:
Phases of a Java Program F
I
Getting to know your Programming Environment using NetBeans L
E
Dissecting a Program 9 M
O
8 Primitive Data Types 9 N
Variables 10
C
Operators 11
A
Arithmetic G
Increment/Decrement U
Relational I
L
Logical and Boolean Logical A
Conditional/Ternary R
Order of Precedence
I
N
Statements and Blocks 15 F
O
Activity – Homeowner Sales 17 R
M
A
Control Flow Statements 18 T
If statement I
If-else statement O
N
If-else-if statement
Switch statement T
E
C
Repetition Control Structures 22 H
While and do-while statements N
For statement O
L
Continue statement
O
Break statement G
Y
Method: Passing Parameters 25
T
Fibonacci Series 26 R
Nested Loop 26 A
I
N
ACTIVITY 27
I
FOR loop: POWER N
Nested Loop & Methods: Diamond G

I
N
Arrays S
1 dimensional array 28 T
I
T
ACTIVITY 30 U
Number Sequence T
HARRY POTTER & THE AMAZING WIZARD E

Data Structures using Java eugene . jay . john. lary . romel . romelyn
3

D
2 dimensional array 32 R

Sorting and searching 34 F


I
Link list 37
L
Queue 37 E
Stack 37 M
O
N
ACTIVITY 41
Stack Operation using Linked List C

A
Database Manipulation 42
G
U
ACTIVITY 45 I
Database Manipulation L
A
R

I
N
F
O
R
M
A
T
I
O
N

T
E
C
H
N
O
L
O
G
Y

T
R
A
I
N
I
N
G

I
N
S
T
I
T
U
T
E

Data Structures using Java eugene . jay . john. lary . romel . romelyn
4
Introduction to Java
D
R
Java was created in 1991 by James Gosling et al. of Sun Microsystems. Initially called Oak, in
honor of the tree outside Gosling's window, its name was changed to Java F
I
because there was already a language called Oak. L
E
The original motivation for Java was the need for platform independent M
language that could be embedded in various consumer electronic products O
N
like toasters and refrigerators. One of the first projects developed using
Java was a personal hand-held remote control named Star 7. C

A
G
Two main deployment environments: U
I
1. The Java Runtime Environment (JRE) supplied by the Java 2 Software Development Kit L
(SDK) contains the complete set of class files for all the Java technology packages, which A
includes basic language classes and GUI component classes. R
2. The web browser. Most commercial browsers supply a Java technology interpreter and I
runtime environment. N
F
O
R
M
A
T
I
O
N

T
E
C
H
N
O
L
O
Phases of a Java Program G
Y

T
R
A
I
N
I
N
G

I
N
Task Tool to use Output S
T
Write the program Any text editor File with .java extension I
Compile the program Java Compiler File with .class extension (Java bytecodes) T
U
Run the program Java Interpreter Program Output T
E

Data Structures using Java eugene . jay . john. lary . romel . romelyn
5
Getting to know your Programming Environment using Netbeans
D
An Integrated Development Environment (IDE) is a programming environment integrated into a R
software application that provides a GUI builder, a text or code editor, a compiler and/or
interpreter and a debugger. F
I
L
Step 1: Using NetBeans 6.8 E
To start the NetBeans IDE in Windows, click on Start Button  Programs  NetBeans M
O
 NetBeans IDE 6.8 or double click on the shortcut icon on the desktop. N

A
G
U
I
L
A
R

I
N
F
O
R
M
A
T
I
O
N

T
E
C
H
SHORTCUT ICON N
O
L
O
G
After opening NetBeans IDE, you will see the splash screen and the graphical user interface Y
(GUI) below.
T
R
A
I
N
I
N
G

I
N
S
T
I
T
U
T
E

Data Structures using Java eugene . jay . john. lary . romel . romelyn
6

D
R

F
I
L
E
M
O
N

A
G
U
I
L
A
R

I
N
F
O
R
M
A
T
I
Step 2: Make a project
O
Click on File  New Project  Java  Java Application  Next N

T
E
C
H
N
O
L
O
G
Y

T
R
A
I
N
I
N
G

I
N
S
Now, a New Application dialog will appear. Edit the Project Name part and type in T
"HelloApplication", then click Finish I
T
U
T
E

Data Structures using Java eugene . jay . john. lary . romel . romelyn
7

D
R

F
I
L
E
M
O
N

A
G
U
I
L
A
R

Step 3. Type the program code then Run File I


N
F
O
R
M
A
T
I
O
N

T
E
C
H
N
O
L
O
G
Launching pad of Y
Java application
T
R
A
I
N
I
N
G

I
N
S
Code / Line no. These lines of code are generated T
I
automatically by NetBeans T
U
T
E

Data Structures using Java eugene . jay . john. lary . romel . romelyn
8

D
R

F
I
L
E
M
Right-click O
code, Select N
Statement
Run File C

A
Output G
U
I
L
A
R

I
N
A common bug in Java program (ex. “Semi-colon expected”). F
O
R
M
A
T
I
O
N

T
E
C
Semi-colon expected H
N
O
L
O
G
Y

T
R
A
I
N
I
N
G

I
N
S
T
I
T
U
T
E

Data Structures using Java eugene . jay . john. lary . romel . romelyn
9
DISSECTING A PROGRAM
D
R
Package is similar to a folder on
your computer that organizes a F
I
set of related classes.
L
E
M
O
Comment is used to N
document a part of the
C
code. It is not part of the
program. A
G
U
I
L
public access specifier indicates Class Main should A
that class Main is accessible to be saved in a file R

other classes from other packages. called Main.java


I
N
F
O
R
M
A
T
I
Prints the text enclosed by O
N
quotation on the screen.
T
E
C
H
8 PRIMITIVE DATA TYPES N
Variables must first be declared before they can be used. A variable's data type determines the O
values it may contain, plus the operations that may be performed on it. L
O
G
1. byte: The byte data type is an 8-bit signed two's complement integer. It has a minimum Y
value of -128 and a maximum value of 127 (inclusive).
2. short: The short data type is a 16-bit signed two's complement integer. It has a T
R
minimum value of -32,768 and a maximum value of 32,767 (inclusive). A
3. int: The int data type is a 32-bit signed two's complement integer. It has a minimum I
value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive). N
I
4. long: The long data type is a 64-bit signed two's complement integer. It has a minimum
N
value of -9,223,372,036,854,775,808 and a maximum value of G
9,223,372,036,854,775,807 (inclusive).
5. float: A single-precision 32-bit floating point. I
N
float h = 340282355999999999999999999999999999999.99f; S
float f = Float.MAX_VALUE; T
6. double: The double data type is a double-precision 64-bit floating point. For decimal I
T
values, this data type is generally the default choice.
U
7. boolean: The boolean data type has only two possible values: true and false. T
8. char: The char data type is a single 16-bit Unicode character. E

Data Structures using Java eugene . jay . john. lary . romel . romelyn
10
Default Values
D
It's not always necessary to assign a value when a field is declared. Fields that are declared R
but not initialized will be set to a reasonable default by the compiler. The following chart
summarizes the default values for the above data types. F
I
L
Data Type Default Value (for fields) E
M
byte 0 O
N
short 0
int 0 C

long 0L A
G
Float 0.0f U
I
double 0.0d
L
Char '\u0000' A
R
String (or any object) Null
I
boolean False N
F
O
R
M
VARIABLES A
Variable is a symbolic name associated with a value that can be changed. T
I
Rules and conventions for naming your variables. O
N
1. Variable names are case-sensitive. A variable name can be any legal identifier — a
sequence of Unicode letters and digits, beginning with a letter, the dollar sign "$", or the T
underscore character "_". E
C
2. Subsequent characters may be letters, digits, dollar signs, or underscore characters. H
3. If the name you choose consists of only one word, spell that word in all lowercase N
letters. If it consists of more than one word, capitalize the first letter of each subsequent O
word. L
O
G
To declare and initialize a variable Y
Data_type name [=initial value];  Value enclosed with square brace ([ ]) is optional.
T
R
Example: A
int rate = 80;  Declare and initialize variable rate I
N
I
float salary;  Declare variable salary N
salary = 15.80;  Initialize variable salary G

I
N
S
T
I
T
U
T
E

Data Structures using Java eugene . jay . john. lary . romel . romelyn
11
OPERATORS
1. Arithmetic D
R
Arithmetic Algebraic Java Description
Operation F
operator expression expression I
Addition + f+7 f+7 Add f and 7 L
Subtraction - p–c p-c Subtract c from p E
M
Multiplication * bm b*m Multiply b by m O
Division / x/y x/y Divide x by y N

Modulus % r mod s r%s Compute the remainder C


by dividing r by s
A
G
public class ArithmeticOperator { U
public static void main( String[] args ){ I
int x = 5, y = 3, prod, sum, diff, quot, remain; L
A
prod = x * y; R
sum = x + y;
diff = x - y; I
N
quot = x / y; F
remain = x % y; O
System.out.println( “Product: “ + prod ); R
System.out.println( “Sum: “ + sum); M
A
System.out.println( “Difference: “ + diff); T
System.out.println( “Quotient: “ + quot ); I
System.out.println( “Remainder: “ + remain); O
N
}
} T
E
C
H
N
O
L
A java package for input / O
import java.io.*; output operation. G
Y

public class ArithmeticOperatorInput { T


public static void main( String[] args ) throws IOException{ R
A
Creating an BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); I
object br int x, y; N
String str; Using function readLine() to read I
intended N
a value to be stored in variable str.
for String G
str = br. readLine();
input values Converting String str to Integer value
x = Integer.parseInt(str); I
Reading and converting String input N
S
y = Integer.parseInt(br.readLine()); to integer value T
I
System.out.println(“Product : “ + (x * y)); T
U
}
T
} E

Data Structures using Java eugene . jay . john. lary . romel . romelyn
12
2. Increment / Decrement Operator
D
Arithmetic Algebraic Description R
Operation
operator expression
Increment ++ x++ Increments x by 1; evaluates the value F
I
of x before it was incremented. L
++x Increments x by 1; evaluates the value E
of x after it was incremented. M
O
Decrement -- x-- Decrements x by 1; evaluates the value N
of x before it was decremented.
C
--x Decrements x by 1; evaluates the value
of x after it was decremented. A
G
U
I
import java.io.*; L
A
R
public class ArithmeticOperator {
public static void main( String[] args ) throws IOException{ I
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); N
F
O
int number1, number2; R
M
number1 = Integer.parseInt(br.readLine()); A
T
I
number1++; O
System.out.println(“Processed value: “ + number1); N

T
number2 = number1++; E
System.out.println(“Processed value of number1: “ + number); C
System.out.println(“Processed value of number2: “ + number2); H
N
O
number2 = ++number1; L
System.out.println(“Processed value of number1: “ + number); O
System.out.println(“Processed value of number2: “ + number2); G
Y
}
} T
R
A
I
N
I
N
G

I
N
S
T
I
T
U
T
E

Data Structures using Java eugene . jay . john. lary . romel . romelyn
13
3. Relational
D
Arithmetic Algebraic Description R
Operation
operator expression
Greater than > a>b Is a greater than b F
I
Greater than or equal to >= a >= b Is a greater than or equal to b L
Less than < a<b Is a less than b E
M
Less than or equal to <= a <= b Is a less than or equal to b O
Equal to == a == b Is a equal to b N

Not equal to != a != b Is a not equal to b C

A
G
4. Logical and Boolean Logical U
I
Logical AND (&&) Logical OR (||) L
NOT P EXCLUSIVE A
P Q R
OR (^)
Boolean Logical AND (&) Boolean Logical inclusive OR (|)
T T T T F F I
N
T F F T F T F
F T F T T T O
F F F F T F R
M
A
The basic difference between Logical and Boolean Logical operators is that T
Logical operators support short-circuit evaluations (or partial evaluations), while I
Boolean Logical doesn't. O
N

T
(5 == 3) && (12%2 >= 6) E
C
Will immediately return FALSE since (5 == 3) yields to false. H
N
(5 == 3) & (12%2 >= 6) O
Will evaluate both condition before returning FALSE. L
O
G
Y
For exclusive OR (^), both operands must always be evaluated in order to
T
calculate the result. R
A
I
5. Conditional / Ternary N
I
The conditional operator ?: is a ternary operator. This means that it takes in three N
arguments that together form a conditional expression. G

I
Syntax : exp1?exp2:exp3 N
S
where T
I
exp1 is a Boolean expression whose result is either true or false
T
exp2 is the value returned if emp1 is true U
exp3 is the value returned if emp1 is false T
E

Data Structures using Java eugene . jay . john. lary . romel . romelyn
14
public class ConditionalOperator {
public static void main( String[] args ){ D
String status = ""; R

int grade = 80; F


I
//get status of the student L
E
status = (grade >= 60)?"Passed":"Fail";
M
O
//print status N
System.out.println( status );
C
}}
A
G
U
I
class ConditionalOperator { L
public static void main( String[] args ){ A
R
int score = 0;
char answer = 'a'; I
N
score = (answer == 'a') ? 10 : 0; F
O
System.out.println("Score = " + score ); R
}} M
A
T
I
O
N
ODER OF PRECEDENCE
T
E
Operator precedence defines the compiler’s order of evaluation of operators so as to
C
come up with an unambiguous result. H
N
O
L
O
G
Y

T
R
A
I
N
I
N
G

I
N
S
Given a complicated expression, T
6 % 2 * 5 + 4 / 2 + 88 - 10 I
T
U
Rewrite the expression and place some parenthesis based on operator precedence T
((6 % 2) * 5) + (4 / 2) + 88 - 10; E

Data Structures using Java eugene . jay . john. lary . romel . romelyn
15
STATEMENTS AND BLOCKS
D
Statements R
Statements are roughly equivalent to sentences in natural languages. A statement forms F
a complete unit of execution. The following types of expressions can be made into a I
statement by terminating the expression with a semicolon (;). L
E
M
Such statements are called expression statements. O
aValue = 8933.234; // assignment statement N
aValue++; // increment statement
C
System.out.println("Hello World!"); // method invocation statement
A
Blocks G
U
A block is a group of zero or more statements between balanced braces and can be used I
anywhere. L
A
R

I
N
F
O
Operators: / * – + R
Compute and display the values for x, y and its average. M
A
T
I
x= – 4a O
N

y = 2(a^2) + 6a T
E
C
H
class compute { N
O
public static void main(String args[]) L
{ Output: O
int a = 5; G
int x = ((5 * a) / (10 * a)) – (4 * a); Y
x = -20
int y = (2 * (a * a)) + (6 * a); y = 80 T
int ave = (x + y ) / 2; average = 30 R
System.out.println(“x = ” + x); A
I
System.out.println(“y = ” + y); N
System.out.println(“average = ” + ave); I
} N
} G

I
N
S
T
I
T
U
T
E

Data Structures using Java eugene . jay . john. lary . romel . romelyn
16
Calculation: Compute for the Gross, Net, Tax
D
Create a program that will compute the gross and netpay of an employee where rate = R
100 and hrs worked = 8. The formula for gross, tax and net is as follows:
F
I
gross = rate * hrs worked L
tax = 5% of gross E
net = gross – tax M
O
N
class grossNet {
C
public static void main(String args[]) {
double gross, net, tax, rate = 100, hrsWorked=8; A
gross = rate * hrsWorked; G
U
tax = gross * .05; Output: I
net = gross – tax; L
System.out.println(“GROSS = ” + gross); GROSS = 800.0 A
System.out.println(“TAX = ” + tax); TAX = 40.0 R

System.out.println(“NET = ” + net); NET = 760.0 I


} } N
F
O
R
M
A
Quadratic Formula using JOptionPane T
I
Create a program that will display the result of the equation O
qF = ax^2 + bx + c N
where
T
a=5, b=2 and c=3.
E
C
The program should accept the value for x. Use JOptionPane.showInputDialog for the H
input value and JOptionPane.showMessageDialog for displaying the result of qF. N
O
L
O
import javax.swing.JOptionPane; G
class quadFormula { Y
public static void main(String args[])
T
{ R
int x, a=5, b=2, c=3, qF; A
String str = JOptionPane.showInputDialog(“Enter a number”); I
N
x = Integer.parseInt(str); I
qF = (a*x*x) + (b * x) + c; N
JOptionPane.showMessageDialog(null, “Computed Value: ” + qF); G
}
I
} N
S
T
I
T
U
T
E

Data Structures using Java eugene . jay . john. lary . romel . romelyn
17
ACTIVITY
Homeowner Sales D
Laboratory problem was downloaded and edited from Thomas L. Brown’s page at R
http://boisdarc.tamu-commerce.edu/~tombrown/lab/cs431/lab1fa06 F
I
L
E
Problem Definition:
M
Design a program that inputs data about a house to be sold and produces output about O
the house and a potential sales transaction. N

Input (Standard system input–the keyboard): A


 homeowners name (String) G
U
 house price (double) and
I
 sales commission rate (int) - for example, 6 will be entered for 6% rate. L
A
R

Output (Standard output–the terminal screen): I


 homeowner’s name N
 house price F
O
 commission
R
 computed selling cost M
A
T
I
Processing O
 Commission is the product of home price and sales commission rate. N
 The selling cost is the sum of home price and the commission.
T
E
C
H
N
O
L
O
G
Y

T
R
A
I
N
I
N
G

I
N
S
T
I
T
U
T
E

Data Structures using Java eugene . jay . john. lary . romel . romelyn
18
CONTROL FLOW STATEMENTS
D
Decision control structures are Java statements that allow us to select and execute specific R
blocks of code while skipping other sections.
F
I
if statement L
The if-then statement tells your program to execute a certain section of code only if a E
particular test evaluates to true. M
O
N
SYNTAX
if( boolean_expression ) if( boolean_expression ) { C
statement; statement1; A
statement2; G
... U
} I
L
A
R
if-else statement
I
The if-then-else statement provides a secondary path of execution when an "if" clause N
evaluates to false. F
O
R
SYNTAX
M
if( boolean_expression ) if( boolean_expression ){ A
statement; statement1; T
else statement2; I
O
statement; ... N
}
else{ T
E
statement1; C
statement2; H
... N
} O
L
O
G
if-else-if statement Y
The statement in the else-clause of an if-else block can be another if-else structure. This T
cascading of structures allows us to make more complex selections. R
A
I
The if-else if statement has the form,
N
if( boolean_expression1 ) I
statement1; N
else if( boolean_expression2 ) G
statement2; I
else N
statement3; S
T
I
Take note that you can have many else-if blocks after an if-statement. The else-block is optional T
and can be omitted. In the example shown above, if boolean_expression1 is true, then the U
program executes statement1 and skips the other statements. If boolean_expression2 is true, T
E
then the program executes statement 2 and skips to the statements following statement3.

Data Structures using Java eugene . jay . john. lary . romel . romelyn
19

D
R
class BlockDemo
{ //begin class block F
I
public static void main(String[] args) L
{ //begin main block E
boolean condition = true; M
O
N
if (condition)
{ // begin block 1 C
System.out.println("Condition is true.");
A
} // end block 1 G
U
else I
L
{ // begin block 2
A
System.out.println("Condition is false."); R
} // end block 2
} //end main block I
N
} //end class block F
O
R
M
A
T
I
O
N

T
E
C
H
N
O
L
O
G
Y

T
R
A
I
N
I
N
G

I
N
S
T
I
T
U
T
E

Data Structures using Java eugene . jay . john. lary . romel . romelyn
20
selection structure – if
D
import javax.swing.JOptionPane; R

F
class selectStruct {
I
public static void main(String args[]) { L
int choice; E
String str; M
O
str = JOptionPane.showInputDialog(“Main Menu \n” + N
“*1+ Name \n” +
“*2+ School \n” + C
“*3+ Course \n” +
A
“*4+ Exit”); G
choice =Integer.parseInt(str); U
if(choice ==1) I
L
JOptionPane.showMessageDialog(null, “iana mel f. galang”); A
else if(choice ==2) R
JOptionPane.showMessageDialog(null, “DFCAIT”);
I
else if(choice ==3)
N
JOptionPane.showMessageDialog(null, “Programming”); F
else if(choice ==4) O
JOptionPane.showMessageDialog(null, “by: Eugene”); R
M
} A
} T
I
O
N

T
E
C
H
N
O
L
O
G
Y

T
R
A
I
N
I
N
G

I
N
S
T
I
T
U
T
E

Data Structures using Java eugene . jay . john. lary . romel . romelyn
21
if: Odd or Even
D
import javax.swing.*; R
class evenOdd
{ F
I
public static void main(String args[]) L
{ E
int num = Integer.parseInt(JOptionPane.showInputDialog(“Enter a number”)); M
int abs=num; O
N

if(num<0) C
abs *= -1;
A
G
int sqr = num * num; U
if(num % 2 == 0) I
L
JOptionPane.showMessageDialog(null,num +” is even\nSquared value = ” + sqr); A
else R
JOptionPane.showMessageDialog(null,num +” is odd\nAbsolute value = ” + abs); I
} N
F
} O
R
M
A
T
I
output O
N

T
E
C
H
N
O
L
O
G
Y

T
R
A
I
N
I
N
G

I
N
S
T
I
T
U
T
E

Data Structures using Java eugene . jay . john. lary . romel . romelyn
22
switch statement
D
Another way to indicate a branch is through the switch keyword. The switch construct R
allows branching on multiple outcomes.
F
I
The switch statement has the form,
L
E
switch( switch_expression ) { M
case case_selector1: O
N
statement1; //
statement2; //block 1 C
. . . //
A
break;
G
case case_selector2: U
statement1; // I
statement2; //block 2 L
A
. . . // R
break;
... I
N
default:
F
statement1; // O
statement2; //block n R
. . . // M
A
break; T
} I
O
N
The body of a switch statement is known as a switch block. Any statement immediately
contained by the switch block may be labeled with one or more case or default labels. T
The switch statement evaluates its expression and executes the appropriate case. E
C
H
To prevent the program from executing statements in the subsequent cases, we use a N
break statement as our last statement. O
L
O
G
Y

T
Repetition Control Structures R
Repetition control structures are Java statements that allows us to execute specific A
blocks of code a number of times. There are three common types of repetition control I
N
structures, the while, do-while and for loops.
I
N
G
 The while and do-while Statements
I
N
The while statement continually executes a block of statements while a particular S
condition is true. Its syntax can be expressed as: T
I
T
while (expression) { U
statement(s) T
} E

Data Structures using Java eugene . jay . john. lary . romel . romelyn
23

D
The while statement evaluates expression, which must return a boolean value. If the R
expression evaluates to true, the while statement executes the statement(s) in the while
block. The while statement continues testing the expression and executing its block until F
I
the expression evaluates to false.
L
E
M
class WhileDemo { O
public static void main(String[] args){ N
int count = 1;
C
while (count < 11) {
System.out.println("Count is: " + count); A
count++; G
U
} I
} L
} A
R

I
N
F
O
R
The difference between do-while and while is that do-while evaluates its expression at
M
the bottom of the loop instead of the top. Therefore, the statements within the do block A
are always executed at least once. T
I
O
class DoWhileDemo { N
public static void main(String[] args){
int count = 1; T
E
do { C
System.out.println("Count is: " + count); H
count++; N
} while (count <= 11); O
L
} O
} G
Y

T
R
A
 The for Statement I
N
I
The for statement provides a compact way to iterate over a range of values. N
Programmers often refer to it as the "for loop" because of the way in which it G
repeatedly loops until a particular condition is satisfied.
I
N
for (initialization; termination; increment) { S
statement(s) T
I
} T
U
T
E

Data Structures using Java eugene . jay . john. lary . romel . romelyn
24
When using this version of the for statement, keep in mind that:
D
The initialization expression initializes the loop; it is executed once, as the loop R
begins.
When the termination expression evaluates to false, the loop terminates. F
I
The increment expression is invoked after each iteration through the loop; it is
L
perfectly acceptable for this expression to increment or decrement a value. E
M
O
class ForDemo { N
public static void main(String[] args){
C
for(int i = 1; i < 11; i++){
System.out.println("Count is: " + i); A
} G
} U
I
} L
A
R

I
 The continue Statement N
The continue statement skips the current iteration of a for, while , or do-while loop. F
O
R
class ContinueDemo { M
public static void main(String[] args) { A
T
I
String searchMe = "peter piper picked a peck of pickled peppers"; O
int max = searchMe.length(); N
int numPs = 0;
T
E
for (int i = 0; i < max; i++) { C
//interested only in p's H
N
if (searchMe.charAt(i) != 'p') O
continue; L
O
//process p's G
Y
numPs++;
} T
System.out.println("Found " + numPs + " p's in the string."); R
A
} I
} N
I
N
G

I
N
 The break Statement S
break terminates the enclosing switch statement, and flow of control transfers to the T
statement immediately following the switch. You can also use the form of the break I
T
statement to terminate a for, while, or do-while loop.
U
T
E

Data Structures using Java eugene . jay . john. lary . romel . romelyn
25
Method: Passing Parameters
D
A method is a set of code which is referred to by name and can be called (invoked) at any point R
in a program simply by utilizing the method's name. Think of a method as a subprogram that
F
acts on data and often returns a value. I
L
Each method has its own name. When that name is encountered in a program, the execution of E
the program branches to the body of that method. When the method is finished, execution M
O
returns to the area of the program code from which it was called, and the program continues on N
to the next line of code.
C

import javax.swing.*; A
class startEnd G
U
{ I
public static void main(String args[]) L
{ A
int x = Integer.parseInt(JOptionPane.showInputDialog(“Enter starting number”)); R

int y = Integer.parseInt(JOptionPane.showInputDialog(“Enter ending number”)); I


disp(x,y); N
} F
O
R
static void disp(int a, int b) //series will be displayed if a <= b M
{ A
String out=””; T
I
for( ; a <= b; a++) O
out = out + a + ” “; N
JOptionPane.showMessageDialog(null,out);
T
} E
} C
H
N
O
L
O
G
Y

T
R
A
I
N
I
N
G

I
N
S
T
I
T
U
T
E

Data Structures using Java eugene . jay . john. lary . romel . romelyn
26
Fibonacci Series
D
The Fibonacci numbers are the numbers in the following sequence: By definition, the first two R
Fibonacci numbers are 0 and 1, and each remaining number is the sum of the previous two.
Some sources omit the initial 0, instead the sequence begins with two 1s. F
I
L
class Fibonacci //1 1 2 3 5 8 13 E
{ M
static void fibo() O
N
{
int x=1, y=1, temp=x+y;; C
System.out.print(x + ” ” + y + ” ” + temp +” “);
A
G
while(temp<13) U
{ I
L
y=x;
A
x=temp; R
temp = x + y;
System.out.print(temp + ” “); I
N
} F
} O
R
M
public static void main(String args[])
A
{ T
fibo(); //method call I
} O
N
}
T
E
C
H
N
O
L
Nested Loop O
The placing of one loop inside the body of another loop is called nesting. When you "nest" two G
Y
loops, the outer loop takes control of the number of complete repetitions of the inner
loop. When working with nested loops, the outer loop changes only after the inner loop is T
completely finished R
A
I
class NestedSeries {
N
public static void main(String args[]) { OUTPUT I
int num1, num2; N
G
1
for(num2 = 1; num2 <= 5; num2++) { 12 I
for(num1 = 1; num1 <= num2; num1++) 123 N
System.out.print(num1); S
1234 T
System.out.println(); 12345 I
} T
} U
}} T
E

Data Structures using Java eugene . jay . john. lary . romel . romelyn
27
ACTIVITY
FOR loop: POWER D
R
Create a program that will compute the power of a number given the base and its exponent. F
Use any looping structure (while, do-while, for) I
L
3 E
Example: 5 M
Base: 5 O
N
Exponent: 3
Result: 125 C

A
G
U
I
ACTIVITY L
Nested Loop & Methods: Diamond A
R

Create a program that will ask the user to choose from 1 to 6 based on the given main menu. I
The output of the program depends on the selected item. N
F
O
A sample screenshot is shown below in which the user had selected number 5. R
M
A
T
I
O
N

T
E
C
H
N
O
L
O
G
Y

T
R
A
I
N
I
N
G

I
N
S
T
I
T
U
T
E

Data Structures using Java eugene . jay . john. lary . romel . romelyn
28
Arrays
D
An array is a container object that holds a fixed number of values of a single type. The length of R
an array is established when the array is created. After creation, its length is fixed. F
I
An array stores multiple data items of the same datatype, in a contiguous block of memory, L
E
divided into a number of slots.
M
O
N

A
G
U
I
L
A
R
An array of ten elements
I
Each item in an array is called an element, and each element is accessed by its numerical index. N
As shown in the above illustration, numbering begins with 0. The 9th element, for example, F
O
would therefore be accessed at index 8. R
M
A
T
Declaring a Variable to Refer to an Array
I
Like declarations for variables of other types, an array declaration has two components: O
the array's type and the array's name. An array's type is written as type[], where type is N
the data type of the contained elements; the square brackets are special symbols
T
indicating that this variable holds an array. The size of the array is not part of its type E
(which is why the brackets are empty). One way to create an array is with the new C
operator. H
N
O
int[] anArray; // declares an array of integers L
anArray = new int[10]; // allocates memory for 10 integers O
G
Y

Initializing, and Accessing an Array T


Assign values to each element of the array: R
A
anArray[0] = 100; // initialize first element
I
anArray[1] = 200; // initialize second element N
anArray[2] = 300; // etc. I
N
G
An index number or subscript is assigned to each member of the array, allowing the
program and the programmer to access individual values when necessary. I
N
S
Each array element is accessed by its numerical index:
T
System.out.println("Element 1 at index 0: " + anArray[0]); I
System.out.println("Element 2 at index 1: " + anArray[1]); T
System.out.println("Element 3 at index 2: " + anArray[2]); U
T
E

Data Structures using Java eugene . jay . john. lary . romel . romelyn
29
Alternatively, you can use the shortcut syntax to create and initialize an array:
int[] anArray = {100, 200, 300, 400, 500, 600, 700, 800, 900, 1000};
D
R
Length of the array is determined by the number of values provided between curly
brackets { and }. F
I
L
E
Array length M
In order to get the number of elements in an array, you can use the length field of an O
N
array. The length field of an array returns the size of the array. It can be used by writing,
arrayName.length C

A
public class ArraySample // 5 6 12 7 3 G
{ U
public static void main( String[] args ){ I
L
int[] ages = {5, 6, 12, 7, 3};
A
for( int i=0; i<ages.length; i++ ){ R
System.out.print( ages[i] );
} I
N
} F
} O
R
M
A
T
I
O
N
1-Dimensional Array T
E
class array13579 C
{ H
public static void main(String args[]) N
{ O
L
int A[] = new int[5]; O
for (int i = 0; i < 5; i++) G
{ Y
A[i] = i*2 + 1; T
System.out.print(A*i+ + ” “); R
} A
} I
N
} I
N
G

I
N
S
T
I
T
U
T
E

Data Structures using Java eugene . jay . john. lary . romel . romelyn
30
ACTIVITY
Number Sequence D
R

Create an array that will store the number sequence 10 20 30 40 to a one dimensional array. F
The program will display the content of the array along with its total. I
L
E
M
O
N
ACTIVITY
C
HARRY POTTER & THE AMAZING WIZARD
http://java.itags.org/java-essentials/52684/ A
G
http://forums.sun.com/thread.jspa?threadID=789887 U
I
L
Declare and initialize a 20-element array. In each element place one of the following characters: A
R
‘W’ – Wizard
‘S’ — Sword I
‘D’ — Demon N
F
‘B’ — Blank – Save spot. O
R
M
Example an array can look like this: A
T
South North I
W S S D B D W B B D W S W D B D S W B S O
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 N

T
You ask the player to select a location in Hogarth Tower. (Choose a number from 0 – 19) That E
places the player at a position in the array. In the example if the user enters a 4 as a starting C
H
position (starting at 0). So, the entry at that position is a B (Blank). N
O
Based on the rules below the player can then move North (add 1 to the array index) or South L
(subtract 1 from the array index). Here are the rules: O
G
(1) For each Blank (B) spot, output the message ‘Safe Place’; 2 points is awarded. Y
(2) For each Wizard (W) spot, output the message ‘You picked up a Wizard’; 3 Points is
Awarded. T
R
(3) For each Sword (S) spot, output the message ‘You picked up a Sword’; 4 Points is A
awarded. I
(4) For each Demon (D) encountered, display the message ‘A demon has attacked’; N
subtract 5 points. I
N
G
The game is over when
(a) The player types in 99 this ends the game. Print out the accumulated points I
N
(b) When the points are below 0 – the player is killed. Display ‘You are killed’ if the point S
garnered by the player is below zero. T
I
Make sure the player does not go beyond the array boundary. The boundary is limited by the T
U
size of the array of 19 elements. T
E

Data Structures using Java eugene . jay . john. lary . romel . romelyn
31
SAMPLE OUTPUT
D
R

F
I
L
E
M
O
N

A
G
U
I
L
A
R

I
N
F
O
R
M
A
T
I
O
N

T
E
C
H
N
O
L
O
G
Y

T
R
A
I
N
I
N
G

I
N
S
T
I
T
U
T
E

Data Structures using Java eugene . jay . john. lary . romel . romelyn
32
2-Dimensional Array
D
One dimensional array can be visualized as a stack of elements; two dimensional arrays can be R
visualized as a multicolumn table or grid.
F
I
By convention, the first subscript is understood to be for rows and the second for columns. By L
default, both subscripts start with zero. E
M
O
The following table illustrates how the subscripts are specified for this array, which has three (3) N
rows and four (4) columns. The array consists of 12 elements (3 x 4).
C

A
0 1 2 3 G
U
0 [0][0] [0][1] [0][2] [0][3] I
L
1 [1][0] [1][1] [1][2] [1][3] A
R
2 [2][0] [2][1] [2][2] [2][3]
I
N
F
O
Declaring a Variable to Refer to an Array R
data_type variable[][] = new data_type[number of rows][number of columns] M
A
T
int values[][] = new int[4][3];  array with 4 rows and 3 columns I
O
N
Initializing, and Accessing an Array
VISUALIZATION T
values[0][0] = 1; E
0 1
values[0][1] = 2; C
0 1 2 H
values[1][0] = 3;
1 3 4 N
values[1][1] = 4; O
L
O
G
int values[][] = {{1,2}, {3,4}};  array with 2 rows and 2 columns
Y

T
R
A
I
N
I
N
G

I
N
S
T
I
T
U
T
E

Data Structures using Java eugene . jay . john. lary . romel . romelyn
33
2-Dimensional Array: Multiplication Table
D
The code below will process and display the 7x7 Multiplication Table R

public class Main { F


I
public static void main(String[] args) { L
int myarr[][]=new int [7][7]; E
M
O
String s="MULTIPLICATION TABLE\n\n\t "; N

for(int x=0; x<7; x++){ C


s =s + "\t " + (x+1);
A
} G
U
s+="\n"; I
L
A
for(int x=0; x<7; x++){ R
s =s + "\t" + (x+1);
I
N
for(int y=0; y<7; y++){ F
myarr[x][y]=(x+1) * (y+1); O
R
M
//if-else is setting the alignment of numbers A
if(myarr[x][y] >= 10) T
s += "\t" + myarr[x][y]; I
O
else
N
s += "\t " + myarr[x][y];
} T
s+="\n"; E
C
} H
N
System.out.println(s); O
L
}
O
} G
Y
//Programmed by: Ms Jovelyn B. Flores
T
R
A
I
N
I
N
G

I
N
S
T
I
T
U
T
E

Data Structures using Java eugene . jay . john. lary . romel . romelyn
34
SORTING AND SEARCHING ALGORITHM USING JAVA
D
R
SORTING F
It is the process of putting a collection of data in some order. Professional programmers use I
one of the java.util.Arrays.sort() methods; they do not write their own, except perhaps in L
E
unusual cases.
M
O
Method Description N

Arrays sort methods C


Arrays.sort(pa); Sorts the elements of the array of a primitive type into A
ascending order using their natural ordering. G
Arrays.sort(pa, from, to); Sorts the elements pa[from]...pa[to-1] of a primitive type into U
ascending order. I
L
A
R

public class SortDemo { I


public static void main(String[] args){ N
F
int[] arrInt = {2, 87, 45, 5, 12, 20, 1, 7}; O
int i; R
M
A
for (i = arrInt.length; --i >= 0; ) { T
for (int j = 0; j < i; j++) { I
if (arrInt[j] > arrInt[j+1]) { O
int temp = arrInt[j]; N

arrInt[j] = arrInt[j+1]; T
arrInt[j+1] = temp; E
} C
H
} N
} O
L
System.out.println("SORTED VALUES"); O
G
for (i = 0; i < arrInt.length; i++) Y
System.out.print(arrInt[i] + " ");
} T
R
} A
//Programmed by: Mr. Jay A. Gofredo I
N
I
N
G

I
N
OUTPUT S
SORTED VALUES T
1 2 5 7 12 20 45 87 I
T
U
T
E

Data Structures using Java eugene . jay . john. lary . romel . romelyn
35

D
The program above can be written using the code below using the statement Arrays.sort(). R

import java.util.*; F
I
public class SortDemo {
L
public static void main(String[] args){ E
int[] arrInt = {2,87,45,5,12,20,1,7}; M
int i; O
N

Arrays.sort(arrInt); C

A
System.out.println("SORTED VALUES IN ASCENDING ORDER"); G
for (i = 0; i < arrInt.length; i++) U
System.out.print(arrInt[i] + " "); I
L
A
System.out.println("\n\nSORTED VALUES IN DESCENDING ORDER"); R
for (i = arrInt.length - 1; i >= 0; i--)
System.out.print(arrInt[i] + " "); I
N
F
System.out.println("\n\n"); O
} R
} M
A
T
I
O
N

T
OUTPUT
E
SORTED VALUES IN ASCENDING ORDER C
1 2 5 7 12 20 45 87 H
N
O
SORTED VALUES IN DESCENDING ORDER L
87 45 20 12 7 5 2 1 O
G
Y

T
R
A
I
N
I
N
G

I
N
S
T
I
T
U
T
E

Data Structures using Java eugene . jay . john. lary . romel . romelyn
36
LINEAR SEARCH
D
Linear searching is a good way to find an element from the array. The array can be of any order, R
it checks whether a certain element (number, string, etc.) is in a specified array or not.
F
I
L
import java.util.*; E
public class SearchValue { M
static int searchItem(final int[] data, final int key) { O
for (int i = 0; i < data.length; ++i) { N

if (data[i] > key) C


return -1;
else if (data[i] == key) A
G
return i; U
} I
return -1; L
A
}
R

public static void main(String[] args) { I


Scanner input = new Scanner(System.in); N
F
final int arr[] = new int[5]; O
R
System.out.println("Enter 5 numbers"); M
A
for (int i = 0; i < arr.length; i++)
T
arr[i] = input.nextInt(); I
O
N

System.out.print("Enter the element to search: "); T


int num=input.nextInt(); E
C
H
int n = searchItem(arr, num);
N
if ((n >= 0) && (n < arr.length)) O
System.out.println(num + " is found at index: " + n); L
else O
G
System.out.println("Not Found"); Y
}
} T
//Programmed by: Mr. Jay A. Gofredo R
A
I
N
I
N
G

I
N
S
T
I
T
U
T
E

Data Structures using Java eugene . jay . john. lary . romel . romelyn
37
LINKED LIST
D
A method of organizing stored data in a computer’s memory or on a storage medium based on R
the logical order of the data and not on its physical order. All stored data are assigned with F
physical address in the memory which the computer uses to locate the information. I
L
E
In each record, there is a field that contains a reference (i.e., a link) to the next record in the
M
sequence. Singly-linked lists contain nodes which have a data field as well as a next field, which O
points to the next node in the linked list. N

A
G
A linked list whose nodes contain two fields: an integer value and a link to the next node U
I
L
A
R

QUEUE I
N
A queue is a particular kind of collection in which the entities in the collection are kept in order F
O
and the principal operations on the collection are the addition of entities to the rear terminal R
position and removal of entities from the front terminal position. This makes the queue a First- M
In-First-Out (FIFO) data structure. In a FIFO data structure, the first element added to the queue A
T
will be the first one to be removed.
I
O
N

T
E
C
H
N
O
L
Representation of a FIFO Queue O
G
Y

STACK T
R
A
A stack is a Last-In-First-Out (LIFO) data structure. A stack is characterized by only two
I
fundamental operations: push and pop. The push operation adds to the top of the list. The pop N
operation removes an item from the top of the list, and returns this value to the caller. I
N
G

I
N
S
T
I
T
U
T
Representation of a LIFO stack E

Data Structures using Java eugene . jay . john. lary . romel . romelyn
38
SAMPLE LINKED-LIST OPERATION
import javax.swing.*; D
class Node { R
int no;
F
Node ptr; I
L
//constructor of class Node E
Node(int n, Node p) M
O
{ N
no = n;
ptr = p; C
} A
G
static void printList(Node list){ //display list U
Node node =list; I
L
String out=”"; A
while (node !=null) R
{
I
out += node + ” –> *" + node.no + "+ ” + node.ptr + “\n” ; N
node =node.ptr; F
} O
JOptionPane.showMessageDialog(null,”link list \n”+out); R
M
} A
T
public static void main(String args[]) { //main method I
O
int noNodes = Integer.parseInt(JOptionPane.showInputDialog(“number of nodes: “)); N
if (noNodes>=2 && noNodes<=5)
{ T
E
int ctr = 1;
C
Node head, dummy, node; H
int value = Integer.parseInt(JOptionPane.showInputDialog(“number ” + ctr)); N
O
L
//1st node created O
node = new Node(value, null); G
head = node; Y
ctr++;
T
R
//2nd upto last node created A
while(ctr<=noNodes) I
N
{ I
value = Integer.parseInt(JOptionPane.showInputDialog(“number ” + ctr)); N
dummy = new Node(value,null); G
node.ptr = dummy;
I
node = dummy; N
ctr++; S
} T
I
T
printList(head); //call static method printList U
} T
} } E

Data Structures using Java eugene . jay . john. lary . romel . romelyn
39
MENU: QUEUE MANIPULATION
D
R
import javax.swing.*;
F
I
class nodeMenu L
{ E
Object info; M
O
nodeMenu link; N

static nodeMenu head, next, tail; C

A
public nodeMenu(Object i, nodeMenu l) //CONSTRUCTOR G
{ U
info = i; I
L
link = l; A
} R

I
static void doAdd() N
{ F
int i = Integer.parseInt(JOptionPane.showInputDialog(“Add Node\nEnter a number”)); O
if(head == null) R
M
{ A
head = new nodeMenu(i,null); T
tail = head; I
O
} N
else
{ T
E
next = new nodeMenu(i,null);
C
tail.link = next; H
tail=next; N
} O
L
} O
G
static void doDisplay() Y
{
T
String output=”"; R
if (head != null) A
{ I
N
next = head; I
while(next!=null) N
{ G
output = output + (next + ” -> ” + next.info + ” ” + next.link + “\n”);
I
next = next.link; N
} S
JOptionPane.showMessageDialog(null, “Display List\n” + output); T
I
} T
else U
JOptionPane.showMessageDialog(null, “List is empty”); T
} E

Data Structures using Java eugene . jay . john. lary . romel . romelyn
40
static void doDelete()
{
D
if(head!=null) R
{
next = head; F
I
head = next.link;
L
next = null; E
JOptionPane.showMessageDialog(null,”Delete Node\nHEAD node deleted”); M
} O
N
else
JOptionPane.showMessageDialog(null,”List is empty”); C
}
A
G
public static void main(String[] args) U
{ I
String menu = “MAIN MENU\n” + L
A
“*1+ Add node\n”+ R
“*2+ Display list\n” +
“*3+ Delete node\n” + I
N
“*4+ Exit”;
F
O
int choice=0; R
M
A
do T
{ I
String str = JOptionPane.showInputDialog(menu); O
N
if(str.equals(“”))
JOptionPane.showMessageDialog(null, “enter a number”); T
else E
{ C
H
choice = Integer.parseInt(str); N
if (choice == 1) O
doAdd(); L
O
else if (choice == 2)
G
doDisplay(); Y
else if (choice == 3)
doDelete(); T
R
else if (choice == 4) A
JOptionPane.showMessageDialog(null, “Programmer: eugene”); I
} N
I
} while(choice != 4);
N
} G
}
I
N
S
T
I
T
U
T
E

Data Structures using Java eugene . jay . john. lary . romel . romelyn
41

D
R

F
I
L
E
M
O
N

A
G
U
I
L
A
R

I
N
F
O
R
M
A
T
I
ACTIVITY O
N
Stack Operation using Linked List
T
E
Create a program using linked list that will ask the user to enter the number of elements of the
C
linked list. Implement the operation involving stacks where elements are added and deleted at H
the top of the stack or at the beginning of the list. N
O
L
O
G
Y

T
R
A
I
N
I
N
G

I
N
S
T
I
T
U
T
E

Data Structures using Java eugene . jay . john. lary . romel . romelyn
42
DATABASE MANIPULATION
D
This program shows a simple data manipulation using MS Access. R

F
I
Glossary of terms: L
1. Connection E
A connection (session) with a specific database. SQL statements are executed and results M
O
are returned within the context of a connection. N

2. ResultSet C
A table of data representing a database result set, which is usually generated by executing a A
statement that queries the database. G
U
3. Statement I
L
The object used for executing a static SQL statement and returning the results it produces. A
R
4. Class.forname
I
Returns the Class object associated with the class or interface with the given string name. N
F
5. DriverManager.getConnection O
Attempts to establish a connection to the given database URL. R
M
A
6. createStatement T
Creates a Statement object for sending SQL statements to the database. I
O
N
7. executeQuery
Executes the given SQL statement, which returns a single ResultSet object. T
E
C
8. executeUpdate H
Executes the given SQL statement, which may be an INSERT, UPDATE, or DELETE N
statement. O
L
O
9. Close G
Releases this Statement object's database and JDBC resources immediately instead of Y
waiting for this to happen when it is automatically closed.
T
R
10. Next A
Moves the cursor down one row from its current position. I
N
I
11. getInt / getString / getDouble / getBoolean / getByte / getFloat N
Retrieves the value of the designated column in the current row of the ResultSet. G

I
12. Exception handling N
A programming language construct designed to handle the occurrence of exceptions (special S
conditions that change the normal flow of program execution). T
I
T
U
T
E

Data Structures using Java eugene . jay . john. lary . romel . romelyn
43
STEPS IN MANIPULATING A DATABASE
D
1. Create a database named student.accdb R

2. Create a table named tblStudInfo. The structure is show below. F


I
L
E
M
O
N

A
3. Add 8 records to the table G
U
I
L
A
R

I
N
F
O
R
M
A
T
I
O
N

4. Open Netbeans  Create a class named DatabaseDemo  Type the code below. T
E
C
H
/** N
* @author Eugene F. Galang O
*/ L
O
G
import java.sql.*;
Y
public class DatabaseDemo {
T
public static void main(String args[]) R
A
{ I
Connection con; N
ResultSet rs; I
N
Statement stmt; G
String qry;
int ctr; I
N
S
String url = T
"jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:/ student.accdb"; I
T
U
T
E
System.out.println("Database manipulation using Access");

Data Structures using Java eugene . jay . john. lary . romel . romelyn
44
try
D
{ R
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection(url,"",""); F
I
L
stmt = con.createStatement(); E
M
qry = "Select * from tblstudinfo"; O
N
rs = stmt.executeQuery(qry);
C

A
//DISPLAY CONTENT OF TABLE tblstudinfo
G
while (rs.next()) U
{ I
System.out.print(rs.getInt("id") + ", "); L
A
System.out.print(rs.getString("sname") + ", "); R
System.out.println(rs.getString("sadd"));
} I
N
F
O
/* R
//CODE FOR APPENDING A RECORD M
A
qry = "INSERT INTO tblStudInfo VALUES(150,’JING’,'ILOCOS')"; T
ctr = stmt.executeUpdate(qry); I
System.out.println("No of rows affected=" + ctr); O
N

T
//CODE FOR UPDATING AN EXISTING RECORD E
qry = "UPDATE tblStudInfo SET sname='JORGE' WHERE id=105"; C
H
ctr = stmt.executeUpdate(qry); N
System.out.println("No of rows affected=" + ctr); O
L
O
G
//CODE FOR DELETING AN EXISTING RECORD. Y
qry = "DELETE FROM tblStudInfo where id=105";
ctr = stmt.executeUpdate(qry); T
R
System.out.println("No of rows affected=" + ctr); A
*/ I
N
I
stmt.close();
N
con.close(); G
}catch(Exception e) { System.out.println("ERROR-->" + e); }
} I
N
} S
T
I
T
U
T
E

Data Structures using Java eugene . jay . john. lary . romel . romelyn
45
ACTIVITY
Database Manipulation D
R

Create a program that will implement the DatabaseDemo code using Menu. Sample menu is F
shown below. I
L
E
MAIN MENU M
O
[1] Add N
[2] Edit C
[3] Delete
[4] View a record A
[5] View all G
U
[6] Exit I
L
A
R
Where:
I
Add  Insert a new record N
Edit  Update an existing record F
Delete  Remove an existing record O
R
View a record  Display the information of a specified user account M
View all  Display all records A
Exit  Terminate system run T
I
O
N

T
E
C
H
N
O
L
O
G
Y

T
REFERENCES R
Webpage URL: A
I
 http://dwcl.wordpress.com/
N
 http://mathbits.com/mathbits/java/methods/Lesson1.htm I
 http://java.sun.com/docs/books/jls/second_edition/html/arrays.doc.html N
 http://www.webopedia.com/TERM/L/linked_list.html G
 http://en.wikipedia.org/wiki/Linked_list I
 http://en.wikipedia.org/wiki/Queue_%28data_structure%29 N
 http://en.wikipedia.org/wiki/Stack_%28data_structure%29 S
T
 http://download.oracle.com/javase/1.5.0/docs/api/index.html?java/lang/Class.html
I
 http://www.dotnetfunda.com/articles/article700-database-operation-in-java-using- T
jdbc-.aspx U
 http://www.csd.abdn.ac.uk/~bscharla/teaching/CS3514/practicals/AnduinBank/src/com T
E
/anduin/Account.java

Data Structures using Java eugene . jay . john. lary . romel . romelyn
46

ADDITIONAL ACTIVITIES D
1. Write a program that mimics a calculator. The program should take two integers and the R

operation to be performed. It should then output the number, the operator and the result. (For F
division, if the denominator is zero, output an appropriate message). I
2. The cost of an international call from New York to Paris is calculated as follows: Connection fee L
$1.99, $2.00 for the first three minutes and $0.45 for each additional minute. Write a program E
that prompts the user to enter the number of minutes the call lasted and outputs the amount M
O
due. Format your output with two decimal places.
N
3. Wire-Gram has hired you as a consultant to build an application that will calculate the cost of
telegram. The application should include a way to enter the message and compute the cost C
based on $4.20 for the first 10 characters and $0.02 for each letter over 10. The total number of
letters and the total cost should display for the person entering the telegram. A
4. Consider a problem in which the percentage commission earned by a salesperson is determined G
U
by a commission code, as shown in the following table:
I
SALESPERSON CODE COMMISSION FACTOR (%) L
R or r 18 A
T or t 10 R
S or s 22
Y or y 10 I
N
The commission is the product of the total sales and the commission factor. Salespeople whose
F
code X receive half of their total sales as their commission. Write a program that accepts the O
total sales and commission code then outputs the total cost to the customer. R
5. Write a program that will compute for the factorial of a supplied number. The factorial of the M
number is the product of those numbers starting from 1 to the supplied number. A
6. Write a program that will derive the sum of the square of series of a number. For example, an T
2 2 2 2 2 I
input of 5 will produce 55 (1 + 2 + 3 + 4 + 5 = 55).
O
7. Write a program that reverses the input number. Formulate an equation to come up with the N
answer. Apply loop statements in your solution. For example, an input of 1234 will produce
4321. T
8. Write a program to convert a number to an English equivalent string formed from the digits. For E
example, 123 represented by “one two three” and 9620 is represented by “nine six two zero”. C
H
9. Write a program that will ask for inputs that will only terminate at an entry of zero. Calculate the
N
average of only positive and negative numbers. O
10. Write a program that takes a one-line sentence as input and then outputs the following L
response: O
o If the sentence ends with the question mark ‘?’ and the input contains an even number G
of characters, then output the word “Yes”. Y
o If the sentence ends with the question mark ‘?’ and the input contains an odd number T
of characters, then output the word “No”. R
o If the sentence ends with the exclamation mark ‘!’ then output the word “Wow”. A
o In all other cases, your program will output the string “You always say” followed by the I
input string enclosed in quotes. N
Your output should all be on one line. Be sure to note that in the last case, your output must I
N
include quotation marks around the echoed input string. Your program should have a loop that G
allows the user to repeat this until the user indicates that he wants to end the program. Your
program does not have to check the input to see that the user entered a legitimate sentence. I
N
S
T
I
T
U
T
E

Data Structures using Java eugene . jay . john. lary . romel . romelyn

Anda mungkin juga menyukai