Title: Chapter 8: Loops, Arrays, Strings
1Chapter 8 Loops, Arrays, Strings
- Loop statements
- do
- while
- for
- Arrays
- declaration, allocation, initialization, access
- multi-dimensional
- heterogeneous
- String class
2Loop Statements
- Sometimes we want to execute a particular piece
of code multiple times - Easy to with a loop
- Java loops
- do loop
- while loop
- for loop
3Do Loop
- Format
- do
- Stmts
- while (Expr)
- results in
- Stmts
- if Expr true done
- Stmts
- if Expr true done
- Stmts
- ...
- Do loop repeats its statement block until the
control expression is false - Always executes at least once
- Expr must be of type boolean
4While Loop
- Format
- while (Expr) Stmt
- results in
- if Expr false done
- Stmt
- if Expr false done
- Stmt
- if Expr false done
- ...
- While loop checks expression, executes statement
if expr true - May not execute at all
- Best to make Stmt a block as in
- while (Expr)
- Stmts
5For Loop
- Format
- for (InitE TestE IncE)
- Stmt
- results in
- InitE
- if TestE false done
- Stmt
- IncE
- if TestE false done
- Stmt
- IncE
- For loop
- executes InitE
- then
- checks TestE, if true
- executes Stmt, IncE
- repeats
- Always executes InitE, may not execute Stmt or
IncE - Use block for Stmt
6Calculate sum of 1 to N
int total 0 int j 1 if (N gt 0) do
total j j while (j lt N)
int total 0 int j 1 while (j lt N)
total j j
int total 0 int j for (j 1 j lt N j)
total j
7Tricky Aspects of Loops
- QWhat if condition to stop loop never met?
- A loop runs FOREVER
- QWhats wrong with the following
- for (j 1 j lt N j)
- total j
- A loop is running the empty statement () for j
from 1 to N
8Arrays
- Not primitive types - no preset values
- Not classes - cant change access methods
- Array is a group of elements (primitive or class)
- same type
- index (numbered) from 0 to size-1
9Array Declaration
- Form
- Type Aname
- Type Aname
- examples
- int numbers
- Button myButtons
- Note declaration creates a pointer to an array,
no space for array allocated
10Array Allocation
- Uses the new operator
- Form
- ArrayVarName new Typesize
- size should be a positive integer
- Allocates group numbered 0 to size-1
- Can be combined with declaration
- int numbers new int10
11Array Initialization
- Can be done at declaration (replaces allocation)
- Type Name Value0, Value1,
- Size of array determined by number of values
- Values must be of same type
- Elements of array set to Value0, Value1, etc. in
order - double taxRates 0.0, 0.08, 0.11, 0.13, 0.28
12Accessing Array Elements
- Form ArrayNameExpression
- can treat as variable of base type of array
- e.g. in array of ints numbers, numbers0 can be
used like any other int (written, assigned, etc.) - Expression should be of type int
- Java may throw an exception if the Expression is
not between 0 and SizeofArray-1
13Array Processing
- Generally done with loops
- Process all (for loop)
- for (j 0 j lt ArraySize j)
- process Aj
- total sum of elements
- total 0
- for (j 0 j lt N j)
- total numbersj
- find smallest
- smallest 0
- for (j 1 j lt N j)
- if (numbersj lt numberssmallest)
- smallest j
14Array Processing
- Search for element (while loop)
- j 0
- while ((j lt ArraySize) (Aj not what we
want)) - j
- Find first non-zero element
- j 0
- while ((j lt N) (Aj 0))
- j
15Multi-Dimensional Arrays
- Forms (2-dimensional)
- Type Name new TypeSize1Size2
- Type Name new TypeSize1Size2
- Example int twodnums new int43
16Non-Rectangular Arrays
- Need not allocate subarrays of same size
- int nonrect new int4
- nonrect0 new int1
- nonrect1 new int2
- nonrect2 new int3
- nonrect3 new int4
17Heterogeneous Arrays
- Arrays may be of class parent type, can hold
different types of elements (as long as parent is
a superclass of type) - Example
- array of Employees
- Employees may be Salaried or Hourly
18public abstract class Employee public float
get2WeekSal() public class SalariedEmployee
extends Employee private float
YearlySalary public float get2WeekSal()
return YearlySalary / 26.0 public class
HourlyEmployee extends Employee private
float HoursPerWeek private float PayPerHour
public float get2WeekSal() return
HoursPerWeek PayPerHour 2
Employee bees new Employee20 totalSal
0.0 for (j 0 j lt 20 j) totalSal
beesj.get2WeekSal()
19Sorting
- Take an array of elements and order them by some
index - array of integers - order from smallest to
largest - array of employees - order alphabetically
- Some methods
- selection sort
- insertion sort
- shell sort
- quick sort
20Selection Sort
Find smallest element, put at position 0 Find
next smallest element, put at position 1 (neednt
look at 0) Find next smallest element, put at
position 2 (ignore 0 and 1) etc. for (j 0 j lt
ArraySize-1 j) smallest j for (k
j1 k lt ArraySize k) if (Arrayk lt
Arraysmallest) smallest k
swap(Arrayj,Arraysmallest)
21Insertion Sort
Like sorting a deck of cards Start with empty
sorted hand Add 1 card in the right place
(sorted hand of 1 card) Add 1 card in the right
place (sorted hand of 2 cards) etc. for (j 1
j lt ArraySize j) k j while ((k gt 0)
(Arrayk lt Arrayk-1))
swap(Arrayk,Arrayk-1) k--
22String Class
- String is a group of characters viewed as a
single entity - A String, lvljsjlfl, (empty string)
- Constructors
- YourString - converts things between to
string - String(char c) - array of chars to string
- String(String s) - makes copy of String s
- Special Method (append)
- abc 123 produces abc123
23String Methods
- boolean equals(Object obj) - true if strings same
- boolean equalsIgnoreCase(Object obj) - same as
equals but upper and lower case chars match (a
equals A) - int compareTo(String s) - compares
alphabetically, -1 if this string less, 0 if
same, 1 if greater - boolean endsWith(String s) - true if string ends
with s - boolean startsWith(String s) - true if string
starts with s - int length() - number of chars in string
24String Methods (cont)
- char charAt(int index) - returns char at position
index - int indexOf(char c) - location of first
occurrence of c - int indexOf(char c, int s) - first occurrence
after loc s - int indexOf(String s) - first occurrence of
string s - int indexOf(String s, int st) - first occurrence
of s after st - these routines return -1 if not found
- there are four similar lastIndexOf routines that
find the last occurrence of the given char or
string - char toCharArray() - returns chars of string as
array - void getChars(int s, int e, char c, int cst) -
returns chars of string from s to e in array c
starting at cst
25String Methods (cont)
- static String valueOf(boolean b) - returns string
corresponding to boolean value - similar versions for char, int, long, float,
double - String substring(int s) - new string using chars
from s on - String substring(int s, int e) - new string,
chars from s to e - String concat(String s) - equivalent to
- String toLowerCase() - new string, all lower case
- String toUpperCase() - new string, all upper case
- String trim() - new string, all leading white
space gone - String replace(char old, char newc) - string with
old replaced by newc
26Related Methods
- static Boolean valueOf(String s) - examines s,
returns the boolean value that can be read from s - similar methods for char, int, long, float double
- error occurs if the string can not be matched to
type