Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 8: Loops, Arrays, Strings Loop statements –do –while –for Arrays –declaration, allocation, initialization, access –multi-dimensional –heterogeneous.

Similar presentations


Presentation on theme: "Chapter 8: Loops, Arrays, Strings Loop statements –do –while –for Arrays –declaration, allocation, initialization, access –multi-dimensional –heterogeneous."— Presentation transcript:

1 Chapter 8: Loops, Arrays, Strings Loop statements –do –while –for Arrays –declaration, allocation, initialization, access –multi-dimensional –heterogeneous String class

2 Loop 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

3 Do 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

4 While 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; }

5 For 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

6 Calculate sum of 1 to N int total = 0; int j = 1; if (N > 0) do { total += j; j++; } while (j <= N); int total = 0; int j = 1; while (j <= N) { total += j; j++; } int total = 0; int j; for (j = 1; j <= N; j++) total += j;

7 Tricky Aspects of Loops Q:What if condition to stop loop never met? –A: loop runs FOREVER Q:What’s wrong with the following: for (j = 1; j <= N; j++); total+= j; –A: loop is running the empty statement (;) for j from 1 to N

8 Arrays Not primitive types - no preset values Not classes - can’t change access methods Array is a group of elements (primitive or class) –same type –index (numbered) from 0 to size-1

9 Array Declaration Form: Type Aname[] Type[] Aname examples: int numbers[] Button[] myButtons Note: declaration creates a pointer to an array, no space for array allocated

10 Array Allocation Uses the new operator Form: ArrayVarName = new Type[size] size should be a positive integer Allocates group numbered 0 to size-1 Can be combined with declaration: int[] numbers = new int[10]

11 Array 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 }

12 Accessing Array Elements Form: ArrayName[Expression] –can treat as variable of base type of array e.g. in array of ints numbers, numbers[0] 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

13 Array Processing Generally done with loops Process all (for loop): for (j = 0; j < ArraySize; j++) process A[j]; total sum of elements: total = 0; for (j = 0; j < N; j++) total += numbers[j]; find smallest: smallest = 0; for (j = 1; j < N; j++) if (numbers[j] < numbers[smallest]) smallest = j;

14 Array Processing –Search for element (while loop) j = 0; while ((j < ArraySize) && (A[j] not what we want)) j++; Find first non-zero element j = 0; while ((j < N) && (A[j] == 0)) j++;

15 Multi-Dimensional Arrays Forms (2-dimensional): Type Name[][] = new Type[Size1][Size2] Type[][] Name = new Type[Size1][Size2] Example int[][] twodnums = new int[4][3]

16 Non-Rectangular Arrays Need not allocate subarrays of same size int[][] nonrect = new int[4][]; nonrect[0] = new int[1]; nonrect[1] = new int[2]; nonrect[2] = new int[3]; nonrect[3] = new int[4];

17 Heterogeneous 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

18 public 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 Employee[20]; totalSal = 0.0; for (j = 0; j < 20; j++) totalSal += bees[j].get2WeekSal();

19 Sorting 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

20 Selection Sort Find smallest element, put at position 0 Find next smallest element, put at position 1 (needn’t look at 0) Find next smallest element, put at position 2 (ignore 0 and 1) etc. for (j = 0; j < ArraySize-1; j++) { smallest = j; for (k = j+1; k < ArraySize; k++) if (Array[k] < Array[smallest]) smallest = k; swap(Array[j],Array[smallest]); }

21 Insertion 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 < ArraySize; j++) { k = j; while ((k > 0) && (Array[k] < Array[k-1])) { swap(Array[k],Array[k-1]); k--; }

22 String 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”

23 String 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

24 String 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

25 String 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

26 Related 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


Download ppt "Chapter 8: Loops, Arrays, Strings Loop statements –do –while –for Arrays –declaration, allocation, initialization, access –multi-dimensional –heterogeneous."

Similar presentations


Ads by Google