Download arrays pepper

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

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

Document related concepts
no text concepts found
Transcript
ARRAYS
Pepper
A PROBLEM WE CAN'T SOLVE (YET)

Consider the following program (input underlined):
How many days' temperatures? 7
Day 1's high temp: 45
Day 2's high temp: 44
Day 3's high temp: 39
Day 4's high temp: 48
Day 5's high temp: 37
Day 6's high temp: 46
Day 7's high temp: 53
Average temp = 44.57142857142857
4 days were above average.

We need the temperatures to compute the average,
and again to tell how many were above average.
2
WHY THE PROBLEM IS TOUGH

We appear to need each input value twice:
once to compute the average
 a second time to count how many were above average


We could read each value into a variable...


However, we don't know how many variables to
declare.
We don't know how many days' weather will be typed
until the program is running.
We need a way to declare many variables in one
step.
3
AN ARRAY
A box that holds many of the exact same type in miniboxes
 A number (index) points to the mini-box
 The number starts at 0
 String is an array of characters
 Ex: Array of money earned in the top row of a
Jeopardy board:

Elements: 100
Index:
0
-100
0
200
300
0
0
1
2
3
4
5
6
DEFINING
AN
ARRAY
100
-100
0
200
300
0
0
0
1
2
3
4
5
6
int[ ] iJeopardy = new int[7];
• 6 is the highest subscript
• Array holds 7 items [called its length]
• Note the number used to create it is the length – 1
• This would create the exact same array, plus put in
initial values:
int[ ] iJeopardy = {0,0,0,0,0,0,0};
GETTING TO AN ARRAY MINI-BOX
•
•
•
•
100
-100
0
200
300
0
0
0
1
2
3
4
5
6
x = iJeopardy[1] ;
means x will get the value -100
iJeopardy[3] = 500;
means the 200 will change to 500
for (int iCount = 0 ;iCount<= 6; iCount++){
iJeopardy[iCount] = 100;
}
means every value will change to 100
iJeopardy[7] will
CRASH
•
(reminder: create this array with:
int[] iJeopardy = new int[7])
GETTING TO AN ARRAY MINI-BOX
100
-100
0
200
300
0
0
0
1
2
3
4
5
6
What will the box look like after these statements:
iX = 3;
iJeopardy[1] = 500;
iJeopardy[4] = intX;
iJeopardy[iX] = 70;
iJeopardy[2+iX] = 600;
iJeopardy[6] = iX+5;
100
500
0
70
3
600
8
CREATE YOUR OWN ARRAY
In BlueJ
Set up an iJeopardy array with 7 elements and set
some values, and then show the values of those
elements by printing them:
Put 600 in the first box
Put 100 in the 4th box (box 3)
CREATE YOUR OWN ARRAY SOLUTION
In BlueJ
Set up an intJeopardy array with 7 elements and
set some values, and then show the values of those
elements by printing them:
int [ ] iJeopardy = new int[7]
iJeopardy[3] = 100
iJeopardy[0] = 600
System.out.println( iJeopardy[3] + “ is the value in
box 3”]
System.out.println( iJeopardy[0] + “ is the value in
box 0”]
INITIALIZING AN ARRAY
100
-100
0
200
300
0
0
0
1
2
3
4
5
6
How do you set all values in the array to 0? Hint: a for
loop from 0 to 6 could give you all the subscripts in the
loop
for (int iCount = 0 ; iCount<=6; iCount++){
iJeopardy[iCount] = 0;
}
MORE USING AN ARRAY
100
-100
0
200
300
0
0
0
1
2
3
4
5
6
What will this do?
System.out.println(“Enter a number”);
iJeopardy[4] = scan.NextInt();
Resolve right side:
• scan.NextInt();
• gets a number from the user
Put into left side variable
• Puts the number into the mini-box above #4
TOTAL THE VALUE HELD

100
-100
0
200
300
0
0
0
1
2
3
4
5
6
Loop through the array mini-boxes adding the values
int intTot = 0;
for (int intCount = 0; intCount <= 6; intCount++){
intTot = iJeopardy[intCount] + intTot;
}
System.out.println(“The total money earned in the top row is “ +
intTot);
PARALLEL ARRAYS
iJeopardy: Cash Value of each box:
100
-100
0
200
300
0
0
0
1
2
3
4
5
6
iPlayed: Played indicator of each box:
True
True
False
True
True
True
false
0
1
2
3
4
5
6
Has Jeopardy question 5 been played?
Does the 0 in box 5 mean the question hasn’t been
played, or that it earned 0 points?
Show a message saying the 0 is the score or not
if (iPlayed[5] == true) {
System.out.println( iJeopardy[5] + “ is the score” );}
else {
System.out.println( iJeopardy[5] + “ is not the score”);}
MINI SUMMARY


What an array is (an indexed set of mini-variables
with one variable name)
How to create an array:
int[ ] iJeopardy = new int[7];
int[ ] iJeopardy = {0,0,0,0,0,0,0};

How to access an array element:
iJeopardy[3]

How to loop through an array:
int intTot = 0;
for (int intCount = 0; intCount <= 6; intCount++){
intTot = iJeopardy[intCount] + intTot;
}
System.out.println(“The total money earned in the top row is
“ + intTot);
PRACTICE ARRAY WORK

Consider the following program (input underlined):
How many days' temperatures? 7
Day 1's high temp: 45
Day 2's high temp: 44
Day 3's high temp: 39
Day 4's high temp: 48
Day 5's high temp: 37
Day 6's high temp: 46
Day 7's high temp: 53
Average temp = 44.57142857142857
4 days were above average.


We need the temperatures to compute the average, and again to tell
how many were above average.
(credit our textbook with this problem and solution)
WEATHER STARTER – HELP TO START
// This program reads several days' temperatures from the user
// and computes the average and how many days were above average.
import java.util.Scanner;
public class Weather {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("How many days' temperatures? ");
int days = console.nextInt();
// create an array to store days' temperatures (as many cells as days)
// initialize a total bucket
for (int i = 0; i < days; i++) {
// read/store each day's temperature
System.out.print(“Enter Day " + (i + 1) + "'s high temp: “);
// save the nextInt into your array of temperatures
// add the temperature to your bucket
}
// calculate the average
// see if each day is above average by doing searching through the array,
// comparing each element to the average
}
}
16
// print the average temp
// print the total count of days above average
WEATHER ANSWER
// This program reads several days' temperatures from the user
// and computes the average and how many days were above average.
import java.util.Scanner;
public class Weather {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("How many days' temperatures? ");
int days = console.nextInt();
int[] temperatures = new int[days];
int sum = 0;
// array to store days' temperatures
for (int i = 0; i < days; i++) {
// read/store each day's temperature
System.out.print("Day " + (i + 1) + "'s high temp: ");
temperatures[i] = console.nextInt();
sum += temperatures[i];
}
double average = (double) sum / days;
int count = 0;
// see if each day is above average
for (int i = 0; i < days; i++) {
if (temperatures[i] > average) {
count++;
}
}
}
17
}
// report results
System.out.println("Average temp = " + average);
System.out.println(count + " days above average");
THE ARRAYS CLASS – A STATIC HELPER

The Arrays class in package java.util has several
useful static methods for manipulating arrays:
Method name
Description
binarySearch(array, value) returns the index of the given
value in this array (< 0 if not
found)
equals(array1, array2)
returns true if the two given
arrays contain exactly the same
elements in the same order
fill(array, value)
sets every element in the array
to have the given value
sort(array)
arranges the elements in the
array into ascending order
toString(array)
returns a string representing the
array, such as "[10, 30, 17]"
18
ARRAYS.TOSTRING

The Arrays.toString method is useful when you want to print
an array's elements.
 Arrays.toString accepts an array as a parameter and
returns the String representation, which you can then print.

Example:
int[] a = {2, 5, 1, 6, 14, 7, 9};
for (int i = 1; i < a.length; i++) {
a[i] += a[i - 1];
}
System.out.println("a is " +
Arrays.toString(a));
Output:
a is [2, 7, 8, 14, 28, 35, 44]
19
ARRAYS.TOSTRING

The Arrays.toString method is useful when you want to print an
array's elements.
 Arrays.toString accepts an array as a parameter and returns
the String representation, which you can then print.

Example:
int[] a = {2, 5, 1, 6, 14, 7, 9};
for (int i = 1; i < a.length; i++) {
a[i] += a[i - 1];
}
System.out.println("a is " + Arrays.toString(a));
Output:
a is [2, 7, 8, 14, 28, 35, 44]
20
TWO DIMENSIONAL ARRAYS
0
100
-100
0
200
300
0
0
1
200
500
66
666
0
6
300
0
1
2
3
4
5
6
int [ ][ ] iJeopardy= new int[2][7] ;
iJeopardy[1][3] is value 666
iJeopardy[0][4] is value 300
What is iJeopardy[0][0] value:
What is iJeopardy[1][6] value:
What is iJeopardy[1][3] value:
What is iJeopardy[2][6] value:
What is iJeopardy[1][7] value:
TWO DIMENSIONAL ARRAYS
0
100
-100
0
200
300
0
0
1
200
500
66
666
0
6
300
0
1
2
3
4
5
6
int [][] iJeopardy= new int[2][7] ;
iJeopardy[1][3] is value 666
intJeopardy[0][4] is value 300
What is intJeopardy[0][0] value: 100
What is intJeopardy[1][6] value: 300
What is intJeopardy[1][3] value: 666
What is intJeopardy[2][6] value: crash
What is intJeopardy[1][7] value: crash
ARRAY OF OBJECTS
You can make an array of objects:
WorldImage [ ] shapes = new WorldImage [4];
shapes[0] = AImage.makeCircle(100,Color.blue);
shapes[1] = AImage.makeRectangle(30,30,Color.yellow);
shapes[0] = shapes[0].place(shapes[1],100,100);
shapes[2] = shapes[0].place(shapes[1],50,50);
shapes[0].show();
0
1
2
3
FUNCTIONS USING ARRAYS
•
An array variable is actually a pointer to the set
of boxes, so…
–
•
Methods can change the mini-boxes in the main
program [though it cannot repoint to another
location]
Defining in method header:
Use [ ] after the variable type, and all else the same
– Don’t know how big it will be, so leave [ ] empty
–
public static int[ ] mymethod(int[ ] arrayin){
ARRAY PARAMETER QUESTIONS



25
Write a method named average that accepts an array of
integers as its parameter and returns the average of the
values in the array.
Write a method named contains that accepts an array of
integers and a target integer value as its parameters and
returns whether the array contains the target value as one
of its elements.
Write a method named roundAll that accepts an array of
doubles as its parameter and modifies each array element
by rounding it to the nearest whole number.
ARRAY PARAMETER ANSWERS
public static double average(int[] numbers) {
int sum = 0;
for (int i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
return (double) sum / numbers.length;
}
public static boolean contains(int[] values, int target) {
for (int i = 0; i < values.length; i++) {
if (values[i] == target) {
return true;
}
}
return false;
}
public static void roundAll(double[] array) {
for (int i = 0; i < array.length; i++) {
array[i] = Math.round(array[i]);
}
}
26
STRING METHODS WITH ARRAYS

These String methods return arrays:
String s = "long book";
Method name
toCharArray()
Description
separates this string
into an array of its
characters
split(delimiter) separates this string
into substrings by the
given delimiting string
Example
s.toCharArray()
returns
{'l', 'o', 'n', 'g', ' ',
'b', 'o', 'o', 'k'}
s.split(" ") returns
{"long", "book"}
s.split("o") returns
{"l", "ng b", "", "k"}
27
STRING/ARRAY PROBLEMS

Write a method named areAnagrams that accepts two Strings
as parameters and returns whether those strings contain the
same letters (in any order).
areAnagrams("bear", "bare") returns true
 areAnagrams("sale", "sail") returns false



Write a method named wordCount that accepts a String as its
parameter and returns the number of words in that string.
Words are separated by spaces.

28
Use any relevant methods from the Arrays class.
wordCount("the quick brown fox") returns 4
MAIN – ARG EXPLAINED!

command-line arguments: Parameters passed to your program
as it is run.
 The parameters are passed into main as an array of Strings.
 The parameters can be typed into a command prompt or
terminal window, or directly in some editors such as DrJava.
public static void main(String[] args) {
for (int i = 0; i < args.length; i++) {
System.out.println("arg " + i + ": " +
args[i]);
}
}

29
Example:
> java ExampleProgram how are you?
arg 0: how
arg 1: are
arg 2: you?
SUMMARY
What an array is (an indexed set of minivariables with one variable name)
 How to create an array
 How to access an array element
 How to loop through an array
 Use arrays as input or output of a method
 Use static arrays class
 Use two dimensional arrays
