Chapter 5 - Southern Methodist University

Download Report

Transcript Chapter 5 - Southern Methodist University

CSE 1341
Arrays & Strings
© 2013 Ken Howard,
Southern Methodist University
Summary of topics covered:
•
•
•
•
•
•
•
•
•
primitive vs. reference types
Creating an array
array type indicator []
Navigating arrays with loops
Enhanced for statements with arrays
Multi-dimensional arrays
Arrays class static methods
args parameter in main method
Characters and Strings
Variable Type Declaration
Every variable must be declared with its type before
it can be used.
The declared type must be either a primitive type:
boolean
char
int
float
byte
short
long
double
….or declared as a reference type:
anything else… (Scanner, String, etc.)
Primitive Types
Declaring and using a variable containing primitive data:
The 8 Primitive Types:
int myAge = 48;
double price = 4.50;
boolean theTruth = true;
X
myAge.isOld();
boolean
char
int
float
byte
short
long
double
Variables for primitives
cannot be used to invoke
methods.
They can only store
information.
Reference Types
Creating an Object and Assigning to a Reference Variable:
CashRegister theCR = new CashRegister();
Call methods on the object referred to by the reference variable:
theCR.calculateTotal();
theCR.calculateChangeOwed(int paymentAmount);
Calling a Method
The class CashRegister
has methods named
calculateTotal and
calculateChangeOwed
Reference Types
Creating multiple objects and assigning each to its own reference variable:
RAM
CashRegister theCR = new CashRegister();
CashRegister theOtherCR = new CashRegister();
theCR.calculateTotal();
theOtherCR.calculateTotal();
Reference Types
Creating an Object and Assigning to a Reference Variable:
String myString = “This is my string”;
String myString2 = new String(“This is my String”);
Scanner myScanner = new Scanner(System.in);
Ball myBall = new Ball();
CashRegister theCR = new CashRegister();
Invoke a method on the object referred to by the reference variable:
myBall.bounce();
theCR.calculateTotal();
theCR.calculateChangeOwed(int paymentAmount);
Arrays
• An array is a collection of elements of the same type.
• Elements can be either primitive types or reference types.
int
0:
1:
2:
3:
4:
5:
6:
…
String
219754
1
21
576
14
1
0:
1:
2:
3:
4:
5:
6:
…
Button
“Foo”
“SMU”
“Peruna”
“Mustang”
0:
1:
2:
3:
4:
5:
6:
…
Arrays
• Every location in an array has an index number.
• Index identifiers begin with zero (0) and are always positive.
• An element of an array can be retrieved with it’s index number.
0:
1:
2:
3:
4:
5:
6:
…
Arrays
• The Array itself is a reference type.
• When you create an array,
– Assign it to a variable.
– Declare the type of data it contains.
• Use primitive or reference type name followed by []
– Give it a variable name to refer to it by.
– Create it using the new keyword.
– Set the size of the array.
String[] myStringArray = new String[5];
int[] myIntArray = new int[10];
Array Creation - Type Indicator
String myString = new String(“SMU”);
Variable myString is
declared as type String.
String[] myStringArray = new String[5];
Variable myStringArray is
declared as type Array of Strings.
Arrays
myIntArray[0]
0
myIntArray[1]
0
myIntArray[2]
0
myIntArray[3]
0
myIntArray[4]
0
myIntArray[5]
0
myIntArray[6]
0
myIntArray[7]
0
myIntArray[8]
0
myIntArray[9]
0
Arrays
myIntArray[2] = 12;
myIntArray[8] = 695;
myIntArray[0]
0
myIntArray[1]
0
myIntArray[2]
12
myIntArray[3]
0
myIntArray[4]
0
myIntArray[5]
0
myIntArray[6]
0
myIntArray[7]
0
myIntArray[8]
695
myIntArray[9]
0
Arrays
Arrays
• An element of an array can be retrieved using its index
location:
int aNumber = myIntArray[3];
0:
1:
2:
3:
4:
5:
6:
…
Retrieves the integer at index
location #3….. the fourth value
Arrays
• The size of an array can be determined using the length
variable:
int sizeOfMyArray = myStringArray.length;
CAREFUL…
The highest index location of an array is its
length minus one.
int x = myStringArray.length;
int y = myStringArray[x];
Doesn’t Exist!!
Array Initializer
• You can create an array and initialize its elements with an array
initializer—a comma-separated list of expressions (called an
initializer list) enclosed in braces.
• Array length is determined by the number of elements in the
initializer list.
• The following statement creates a five-element array with index
values 0–4
int[] n = { 10, 20, 30, 40, 50 };
• Element n[0] is initialized to 10, n[1] is initialized to 20, and
so on.
• When the compiler encounters an array declaration that includes
an initializer list, it counts the number of initializers in the list to
determine the size of the array, then sets up the appropriate new
operation “behind the scenes.”
Create a 10-element array and assign to each element
one of the even integers from 2 to 20 (2, 4, 6, …, 20):
final
modifier:
Value
can’t be
changed
Sample Problem with Array Solution
• Roll a die 6000 times
• Tally the 1’s, 2’s, 3’s, 4’s, 5’s and 6’s.
• Report the total frequency for each possible die roll.
index
locations
0..6
Increment
the integer
value at this
index
location.
Sum the values contained in a 10-element integer array:
Sample Problem with Array Solution
• Roll a die 6000 times
• Tally the 1’s, 2’s, 3’s, 4’s, 5’s and 6’s.
• Report the total frequency for each possible die roll.
int x = myStringArray.length;
int y = myStringArray[x];
Will compile, but during runtime…
ArrayIndexOutOfBoundsException
Enhanced for Statement
• Iterates through the elements of an array without using a counter, thus
avoiding the possibility of “stepping outside” the array.
• Syntax:
for ( parameter : arrayName )
statement
– where parameter has a type and an identifier, and arrayName is the array
through which to iterate.
– Parameter type must be consistent with the type of the elements in the array.
• Can be used only to obtain array elements—it cannot be used to modify
elements.
• Can be used in place of the counter-controlled for statement whenever
code looping through an array does not require access to the counter
indicating the index of the current array element.
Enhanced for statement to sum the integers in an array of grades:
Passing Arrays to Methods
0: 1
1: 2
2: 3
3: 4
4: 5
public class MyClass
{
public static void main(String[] args)
{
int[] myArray = {1, 2, 3, 4, 5};
otherMethod(myArray);
System.out.println(myArray[1]);
}
public static void otherMethod(int[] passedArray)
{
passedArray[1] = 99;
System.out.println(passedArray[1]);
}
}
What will display?
Multidimensional Arrays
• Multidimensional arrays with two dimensions often
represent tables of values consisting of information
arranged in rows and columns.
– To identify a particular table element, we must specify two
indices—the first identifies the element’s row and the second its
column.
• Arrays that require two indices to identify an element are
called two-dimensional arrays.
• Multidimensional arrays can have more than two
dimensions.
– Java does not support multidimensional arrays directly, but it does
allow you to specify one-dimensional arrays whose elements are
one-dimensional arrays, thus achieving the same effect.
Two Dimensional Arrays
String[][] myArray = new String[4][3];
myArray[0][1] = “Foo”
0
0 null
1 null
2 null
3 null
myArray[row][col]
--------------------------myArray[0][1]
1
Foo
null
null
null
2
null
null
null
null
Two Dimensional Arrays
public class Practice
{
public static void main(String[] args)
{
String[][] myArray = new String[4][3];
myArray[0][1] = "Foo”;
for(int i = 0; i < 4; i++)
{
for(int j = 0; j< 3; j++)
{
System.out.printf("\nLocation %d , %d contains: %s", i , j, myArray[i][j]);
}
}
}
}
Two Dimensional Arrays
• Figure 6.11 shows a two-dimensional array named a
that contains three rows and four columns (i.e., a
three-by-four array).
• In general, an array with m rows and n columns is
called an m-by-n array.
Two Dimensional Arrays
• A two-dimensional array b with two rows and two columns
could be declared and initialized with nested array initializers
as follows:
int[][] b = { { 1, 2 }, { 3, 4 } };
• The initial values are grouped by row in braces.
Array with Different Row Lengths
String[][] myArray = new String[4][];
myArray[0] = new String[5];
myArray[1] = new String[2];
myArray[2] = new String[3];
myArray[3] = new String[3];
myArray[3][2] = “Foo”;
0
1
null
null
null
null
null
2
null
null
null
3
null
null
Foo
0
1
2
3
null
4
null
Multi Dimensional Array Example
• The Example below demonstrates initializing two-dimensional
arrays with array initializers and using nested for loops to
traverse the arrays (i.e., manipulate every element of each
array).
Passing Data Into Your Java Program
public class Practice
{
public static void main(String[] args)
{
System.out.println(args[0]);
args is an array of Strings.
}
}
Command line arguments.
C:\>java MyClass Foo
TRY THIS:
Write a program that displays all command line arguments, where
you don’t know how many values will be passed in.
(Hint: args.length gives the size of the array)
Class Arrays
• Class Arrays helps you avoid reinventing the wheel by
providing static methods for common array manipulations.
Remember: static methods are methods that are invoked directly on the
class by specifying the class name, a period, and the name of the method
(with its parameters).
Pass an int, double, float, short,
long, char, or byte array.
Sorts in ascending order.
import java.util.Arrays;
public class Practice {
public static void main(String[] args){
int[] myArray = {1, 3, 5, 2, 6, 4};
for(int i = 0; i < myArray.length; i++)
System.out.println(myArray[i]);
Arrays.sort(myArray);
Arrays.sort(myArray);
for(int i = 0; i < myArray.length; i++)
System.out.println(myArray[i]);
}
}
Class Arrays
Arrays.binarySearch(myArray, value);
import java.util.Arrays;
public class Practice
{
public static void main(String[] args)
{
int x;
int[] myArray = {1, 3, 5, 2, 6, 5, 5, 77, 2, 5};
Arrays.sort(myArray); //Must sort before using binary search
Pass an int, double, float,
short, long, char, or byte array.
PLUS…
a single value of the same type
(what you’re searching for)
Returns the index value.
x =Arrays.binarySearch(myArray,77);
System.out.println("Found 77 at index location " + x);
//IF MORE THAN ONE FOUND, UNRELIABLE WHICH IS RETURNED
//BECAUSE BINARY SEARCH DOES NOT SEARCH FRONT TO BACK
x =Arrays.binarySearch(myArray,5);
System.out.println("Found 5 at index location " + x);
//IF NOT FOUND, Returns -(arraySize++)
x =Arrays.binarySearch(myArray,9);
System.out.println("Found 9 at index location " + x);
}
}
Class Arrays
Arrays.equals(myArray, myOtherArray);
import java.util.Arrays;
public class Practice
{
public static void main(String[] args)
{
int x;
int[] myArray = {1, 3, 5, 7};
int[] myOtherArrayOne = {1, 3, 5, 7};
int[] myOtherArrayTwo = {1, 3, 5};
int[] myOtherArrayThree = {1, 3, 7, 5};
//RETURNS true
System.out.println(Arrays.equals(myArray,myOtherArrayOne));
//RETURNS false
System.out.println(Arrays.equals(myArray,myOtherArrayTwo));
//RETURNS false
System.out.println(Arrays.equals(myArray,myOtherArrayThree));
}
}
Compares two arrays. Returns
true if both are equal size and
all elements at each index
location are equal.
Class Arrays
Arrays.fill(myArray, value);
import java.util.Arrays;
public class Practice
{
public static void main(String[] args)
{
int[] myArray = {1, 3, 5, 7};
Arrays.fill(myArray,9);
for(int i = 0; i < myArray.length; i++)
System.out.println(myArray[i]);
}
}
Replaces all elements of the
array with value. The type of
value must match the type of
the array.
System.arraycopy
System.arraycopy(myArray, startIndex, otherArray, destIndex, numElements);
public class Practice
{
public static void main(String[] args)
{
int[] myArray = {1, 3, 5, 7};
int[] newArray = new int[4];
int[] otherArray = new int[2];
int[] yetAnotherArray;
System.arraycopy(myArray,0,newArray,0,4);
for(int i = 0; i < newArray.length; i++)
System.out.println(newArray[i]);
//THIS WILL THROW IndexOutOfBoundsException
System.arraycopy(myArray,0,otherArray,0,4);
//THIS WON'T COMPILE BECAUSE yetAnotherArray IS NULL
//System.arraycopy(myArray,0,yetAnotherArray,0,4);
}
}
Copies numElements elements
from myArray (starting at
startIndex) to otherArray
(starting at destIndex)
Characters and Strings
• Characters are the fundamental building blocks
of Java source programs.
• A character literal is an integer value
represented as a character in single quotes.
• The value of a character literal is the integer
value of the character in the Unicode character
set.
Characters and Strings
• A string may include letters, digits and various
special characters, such as +, -, *, / and $.
• A string is an object of class String.
• String literals (stored in memory as String
objects) are written as a sequence of characters
in double quotation marks.
• A string may be assigned to a String
reference.
Class String
• Class String is used to represent strings in Java.
Some String methods
//Returns the size of the String:
myString.length()
returns an int
//Return a char at location int:
myString.charAt(int)
returns a char
//Return a set of characters as a char array:
myString.getChars(int,int,char[],int)
sourceBegin, sourceEnd, destArray, destBegin
More String methods
myString.equals(anotherString)returns boolean
myString.equalsIgnoreCase(anotherStri
ng)
myString.compareTo(anotherString)
returns:
negative number if myString < anotherString
positive number if myString . anotherString
zero if myString == anotherString
When the computer compares strings, it
actually compares the numeric codes of
the characters in the strings.
More about String comparison
• When primitive-type values are compared with ==,
the result is true if both values are identical.
• When references are compared with ==, the result is
true if both references refer to the same object in
memory.
• Java treats all string literal objects with the same
contents as one String object to which there can be
many references.
More about String methods
String s = “test“;
Length
• i = s.length()
length of the string s.
Comparison (note: use these instead of == and !=)
• i = s.compareTo(t)
compares to s.
returns <0 if s<t, 0 if ==, >0 if s>t
• i = s.compareToIgnoreCase(t) same as above, but upper and lower
case are same
• b = s.equals(t)
true if the two strings have equal values
• b = s.equalsIgnoreCase(t)
same as above ignoring case
• b = s.startsWith(t)
true if s starts with t
• b = s.startsWith(t, i)
true if t occurs starting at index i
• b = s.endsWith(t)
true if s ends with t
More about String methods
Searching -- Note: All "indexOf" methods return -1 if the string/char is not found
• i = s.contains(cs)
True if cs can be found in s.
• i = s.indexOf(t)
index of the first occurrence of String t in s.
• i = s.indexOf(t, i)
index of String t at or after position i in s.
• i = s.indexOf(c)
index of the first occurrence of char c in s.
• i = s.indexOf(c, i)
index of char c at or after position i in s.
• i = s.lastIndexOf(c)
index of last occurrence of c in s.
• i = s.lastIndexOf(c, i) index of last occurrence of c on or before i in s.
• i = s.lastIndexOf(t)
index of last occurrence of t in s.
• i = s.lastIndexOf(t, i) index of last occurrence of t on or before i in s.
Getting parts
• c = s.charAt(i)
char at position i in s.
• s1 = s.substring(i)
substring from index i to the end of s.
• s1 = s.substring(i, j)
substring from index i to BEFORE index j of s.
More about String methods
Creating a new string from the original
• s1 = s.toLowerCase() new String with all chars lowercase
• s1 = s.toUpperCase() new String with all chars uppercase
• s1 = s.trim()
new String with whitespace deleted from front and
back
• s1 = s.replace(c1, c2) new String with all c1 characters replaced by
character c2.
• s1 = s.replace(cs2, cs3)
new String with all cs2 substrings replaced
by cs3.
Static Methods for Converting to String
• s = String.valueOf(x)
Converts x to String, where x is any type
value (primitive or object).
• s = String.format(f, x...)
[Java 5] Use format f to convert variable
number of parameters, x to a string.
Regular Expressions (there are also regex for String)