Download ppt3

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Arrays
•
Array is a data structure that represents a collection of the
same type of data.
•
A "fixed length list".
double[] myList = new double[10];
myList
reference
Array reference
variable
Array element at
index 5
myList[0]
5.6
myList[1]
4.5
myList[2]
3.3
myList[3]
13.2
myList[4]
4
myList[5]
34.33
myList[6]
34
myList[7]
45.45
myList[8]
99.993
myList[9]
2
11123
Element value
Declaring and Creating Arrays
datatype[] arrayRefVar = new datatype[arraySize];
double[] myList = new double[10];
The new keyword is a Java operator that
creates the object.
new calls a constructor, which initializes the new
object.
Everything in java is class-based. So we need to make
objects (instances) for anything that isn’t a primitive type.
ints, doubles, chars are primitive types
Arrays aren’t
3
Declaring, creating, initializing Using the
Shorthand Notation
double[] myList = {1.9, 2.9, 3.4, 3.5};
This shorthand notation is equivalent to the following
statements:
double[] myList = new double[4];
myList[0] = 1.9;
myList[1] = 2.9;
myList[2] = 3.4;
myList[3] = 3.5;
4
• Can do:
• int[] anArr = {1,
• int[] anArr = new
anArr[0] = 1;
anArr[1] = 9;
anArr[2] = 4;
anArr[3] = 3;
• Can’t do:
• int[] anArr = new
anArr = {1, 9, 4,
9, 4, 3};
int[4];
int[4];
3}; //can’t initialize
// after
initializing
• anArr[4] = 5; //Arrays are FIXED LENGTH!
Structural Repetition using Loops
Often used when executing code for each element in a
collection of data
double[] data = {3.2, 4.1, 2.1};
double sum = 0;
for (double echidnas : data) {
sum += echidnas;
}
System.out.println(sum);
What if we want to add values to the end of our array?
public static int[] addingarrays(int[] arr1, int[] arr2){
int x = arr1.length;
int y = arr2.length;
int[] newarr = new int[x+y];
for (int ind=0;ind<arr1.length;ind++) {
newarr[ind]= arr1[ind];
System.out.println(newarr[ind]);
}
for (int ind=0;ind<arr2.length; ind++){
newarr[x+ind] = arr2[ind];
System.out.println(newarr[x+ind]);
}
System.out.println(newarr);
work?
return newarr;
}
//will this
java.util.Arrays
import java.util.Arrays;
public class ArrayMethods {
public static void print(int[] newarr) {
System.out.println(Arrays.toString(newarr));
}
// ...
}
Contains useful methods for dealing with Arrays, including:
 Sort
Arrays.sort(values);
 binarySearch
int index = Arrays.binarySearch(values,3);
 Equals
Arrays.equals(values,array2) // sees if values inside of array are equal
 Fill
int[] array = new int[5];
Arrays.fill(array,0);
 toString
No sum!! You have to write your own.
To Try:
1.Write a method that takes as input parameters two
arrays of ints, each array being the same length
(obtained by arr.length).
• The method creates a new array, twice as long, with the
two arrays joined so that:
• the first value is arr[0], the second value is arr2[0], the third
value is arr[1], the fourth is arr2[1], etc.
• It returns that new array.
1.Write a method that takes as input an array of
integers, in order, and a number. The method
should create a new array, with the number
inserted into the correct (ordered) location. It
should return this array.
public static void main (String[] args) {
int [] k = {3,2,5,7};
int[] m = {8,6,4,9};
int[] x = f1(k,m);
System.out.println(Arrays.toString(x));
int n[] = {3,7,12,18,27,47,52};
int[] y = f2(n,42);
System.out.println(Arrays.toString(y));
}
public static int[] f1(int[] arr1, int[] arr2){
int x = arr1.length;
int[] newarr = new int[x*2];
for (int i=0;i<arr1.length;i++) {
newarr[i*2]= arr1[i];
newarr[i*2+1] = arr2[i];
}
return newarr;
}
public static int[] f2(int[] arr1, int x){
int y = arr1.length;
int[] newarr = new int[y+1];
int a = 0;
for (int i=0;i<arr1.length;i++) {
if ((arr1[i] > x) && (a==0)) {
newarr[i] = x;
a = 1;
}
newarr[i+a]= arr1[i];
}
return newarr;
Recursion: Looping
public static int r1(int x) {
if (x == 0) {
return(x);
}
else {
}
return(x + r1(x-1));
}
System.out.println(r1(5));
• Remember – Every function call can be replaced with
what the function returns
• If what is returned includes another function call, we must
calculate what that function call returns before we know
what is returned from the original function call
• All initialization must happen OUTSIDE the function
(method)
• The only thing that happens only once in a recursive function
is the stopping condition
• Look at what is returned from each function call
What is our stopping condition?
public static int r4(int x, int y) {
if (x == 1) {
return(0);
}
else if (y%x == 0) {
return(1 + r4(x-1,y));
}
else {
return(0+ r4(x-1,y));
}
}
System.out.println(r4(11,12));
public static int r3(int x, int[] y, int z) {
if (z == y.length) {
return(0);
}
else if (y[z] == x) {
return(1 + r3(x,y,z+1));
}
else {
return(r3(x,y,z+1));
}
}
int[] vb = {1,0,1,1,0,0,1,0,1};
System.out.println(r3(1,vb,0));
Strings
• A type, but extended
• A class that encompasses a character array and
provides many useful behaviors
• Chapter 9 (for the book people)
• Strings are IMMUTABLE
String Accessors
java.lang.String
+length(): int
 Returns the number of characters in this string.
+charAt(index: int): char
 Returns the character at the specified index from this
string.
message = "Welcome";
message.length()
(gives us what?)
15
Retrieving Characters in a String
• Cannot use message[0]
• (strings are immutable)
• Use message.charAt(index)
• Index starts from 0
Indices
0
1
2
3
4
5
6
message
W
e
l
c
o
m
e
message.charAt(0)
7
8
9
t
o
message.length() is 15
16
10 11 12 13 14
J
a
v
a
message.charAt(14)
String Comparisons
String s1 = new String("Welcome“);
String s2 = "Welcome";
if (s1 == s2) {
// whaddaya think?
}
if (s1.equals(s2)){
// do s1 and s2 have the same contents?
}
17
String Comparisons, cont.
• compareTo(Object object)
String s1 = new String("Welcome“);
String s2 = "hello";
if (s1.compareTo(s2) > 0) {
// is s1 greater than s2?
}
else if (s1.compareTo(s2) == 0) {
// do s1 and s2 have the same contents?
}
else {
// s1 is lexicographically less than s2
}
18
Strings are Immutable!
• Immutable means we can’t change them.
• Can’t do:
String str = “hello”;
str[3] = ‘b’;
• So then why does this work?
String str = "Hello";
System.out.println(str); //Prints Hello
str = "Help!";
System.out.println(str); //Prints Help!
Why can I do this?
(Or, isn’t this mutating the string?)
String str = "Mississippi";
System.out.println(str); //Prints Mississippi
str = str.replace("i", "!");
System.out.println(str); //Prints M!ss!ss!pp!
String methods:
charAt(int index) – gets the character at the index within the string and returns the char
indexOf(char c)- sees if a character is within a string and returns an int representing the index
indexOf(char c, int fromindex) - sees if a character is within a string from fromindex
onwards
length() – returns number of characters in a string (note that for strings this is a method. What is it
for arrays?)
substring(int beginindex) – extracts and returns a substring from a string, starting at
beginindex and going to the end of the string
substring(int beginindex, int endindex) – extracts and returns a substring from
beginindex to endindex
toLowerCase() – returns a string that is the lower case version of the string
toUpperCase() – returns a string that is the upper case version of the string
trim() - removes white space (space char) from both ends of a string and returns that string
toCharArray() – converts string to character array and returns that array
equalsIgnoreCase(String otherstring) – compares string with otherstring and returns
Boolean value (true if equals, false if doesn’t)
compareToIgnoreCase(String otherstring) – compares string with otherstring, and returns
int (>0 if string is “greater”, 0 if equal, and <0 if “less than”.
toString() method
• Printing objects:
– If you print an object that doesn’t have a toString() method, you print out the hash
representation of the object
• Not what we want.
– All java built-in objects have a toString method implemented.
• E.g.,
double[] x = {3.2, 7.1, 8.83, 2.5};//Color is a built-in java class -RGB
System.out.println(Arrays.toString(v));
• Will print out:
[3.2, 7.1, 8.83, 2.5]
(this is the string that the toString method explicitly created for Arrays and returned.)
toString() (Better Example)
• Classes should all have there own toString method written
• So if we create an object of the class, we can print out the object.
• Example:
• Java has a built-in class for Color objects.
• Every color object has 3 fields:
• the amount of red,
• the amount of green,
• and the amount of blue.
• To make an object of type color:
Color x = new Color( 255, 0, 0 );
• The color class has a built in toString method (all Java classes do)
• So we can now print out color objects using System.out.println(x)
• We’ll get:
java.awt.Color[r=255,g=0,b=0]
• Also happens with concatenation, e.g.,:
Color x = new Color( 255, 0, 0 );
String str = “This is color: “;
str += x;
•
toString() is a method that you should write when you create a class definition.
•
will automatically be used as above.
Try
• Write a function that takes as an input parameter a string, and prints
out every value in the string backwards. So, for instance, if the input
string is “yranib”, the function should print out:
b
i
n
a
r
y