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

Slides:



Advertisements
Similar presentations
Intro to Scala Lists. Scala Lists are always immutable. This means that a list in Scala, once created, will remain the same.
Advertisements

Chapter 8: Arrays.
Chapter 7 Strings F To process strings using the String class, the StringBuffer class, and the StringTokenizer class. F To use the String class to process.
1 Working with String Duo Wei CS110A_ Empty Strings An empty string has no characters; its length is 0. Not to be confused with an uninitialized.
Chapter 7 Strings F Processing strings using the String class, the StringBuffer class, and the StringTokenizer class. F Use the String class to process.
Written by: Dr. JJ Shepherd
CERTIFICATION OBJECTIVES Use Class Members Develop Wrapper Code & Autoboxing Code Determine the Effects of Passing Variables into Methods Recognize when.
String and Lists Dr. Benito Mendoza. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list List.
Data Types in Java Data is the information that a program has to work with. Data is of different types. The type of a piece of data tells Java what can.
Strings and Arrays The objectives of this chapter are:  To discuss the String class and some of its methods  To discuss the creation and use of Arrays.
Chapter 10.
Sanjay Goel, School of Business, University at Albany, SUNY 1 MSI 692: Special Topics in Information Technology Lecture 4: Strings & Arrays Sanjay Goel.
J.43 ARRAYS  A Java array is an Object that holds an ordered collection of elements.  Components of an array can be primitive types or may reference.
Loops Notes adapted from Dr. Flores. It repeats a set of statements while a condition is true. while (condition) { execute these statements; } “while”
1 Arrays b An array is an ordered list of values An array of size N is indexed from zero to N-1 scores.
Java Syntax Primitive data types Operators Control statements.
Loops – While, Do, For Repetition Statements Introduction to Arrays
CSM-Java Programming-I Spring,2005 String Handling Lesson - 6.
Strings, Etc. Part I: Strings. About Strings There is a special syntax for constructing strings: "Hello" Strings, unlike most other objects, have a defined.
Lab session 3 and 4 Topics to be covered Escape sequences Escape sequences Variables /identifiers Variables /identifiers Constants Constants assignment.
28-Jun-15 String and StringBuilder Part I: String.
Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4.
COMP 110 Introduction to Programming Mr. Joshua Stough September 10, 2007.
Sanjay Goel, School of Business, University at Albany, SUNY 1 MSI 692: Special Topics in Information Technology Lecture 4: Strings & Arrays Sanjay Goel.
TODAY’S LECTURE Review Chapter 2 Go over exercises.
From C++ to Java A whirlwind tour of Java for C++ programmers.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
String Manipulation Chapter 15 This chapter explains the String facilities. You have already seen some of the main methods of the String class.
M180: Data Structures & Algorithms in Java Arrays in Java Arab Open University 1.
Working with string In java Four classes are provided to work with String:1) String 2)String Buffer 3)String Tokenizer 4)String Builder Note: An object.
Comparison-Based Sorting & Analysis Smt Genap
CHAPTER 9 Text Processing and More about Wrapper Classes Copyright © 2016 Pearson Education, Inc., Hoboken NJ.
Chapter 3: Classes and Objects Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved Java’s String Class.
CSC 212 Object-Oriented Programming and Java Part 2.
School of Computer Science & Information Technology G6DICP - Lecture 4 Variables, data types & decision making.
Arrays An array is a data object that can hold multiple objects, all of the same type. We can think of an array as a storage box which has multiple compartments.
CSI 3125, Preliminaries, page 1 String. CSI 3125, Preliminaries, page 2 String Class Java provides the String class to create and manipulate strings.
Chapter 3A Strings. Using Predefined Classes & Methods in a Program To use a method you must know: 1.Name of class containing method (Math) 2.Name of.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter Array Basics.
Array Declarations Arrays contain a fixed number of variables of identical type Array declaration and allocation are separate operations Declaration examples:
Java String 1. String String is basically an object that represents sequence of char values. An array of characters works same as java string. For example:
Written by: Dr. JJ Shepherd
17-Feb-16 String and StringBuilder Part I: String.
1 Unit-2 Arrays, Strings and Collections. 2 Arrays - Introduction An array is a group of contiguous or related data items that share a common name. Used.
Chapter 5: Arrays in Java. The objectives of this chapter are:  1. To discuss the creation and use of Arrays.   2. To continue to use the String class.
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
Windows Programming Lecture 03. Pointers and Arrays.
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
2 Arrays Array is a data structure that represents a collection of the same type of data. A "fixed length list".
Strings, StringBuilder, and Character
2.5 Another Java Application: Adding Integers
EKT 472: Object Oriented Programming
University of Central Florida COP 3330 Object Oriented Programming
Multiple variables can be created in one declaration
Programming in Java Text Books :
String and String Buffers
String Handling in JAVA
String and StringBuilder
Object Oriented Programming
String and StringBuilder
String and StringBuilder
Java – String Handling.
Recap Week 2 and 3.
String and StringBuilder
Strings in Java.
In Java, strings are objects that belong to class java.lang.String .
Arrays.
Presentation transcript:

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

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

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

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

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

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;

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

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

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

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]

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 }

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

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;

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++;

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]

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];

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

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();

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

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]); }

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

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”

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

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

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

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