AP COMPUTER
SCIENCE
AN INTERESTING PROBLEM
⦿
Exercise 1: Write a program to ask the user for a
number of days, then read in that many days’ sales
and output the total
⦿
Exercise 2: Modify the above program to print out
the total
and
the average of the days’ sales
ARRAYS
⦿
If we want to hold on to a group of objects in
Java, we can use a structure called an array
⦿
An array is basically a table of variables:
ARRAYS
⦿
Arrays are declared like normal variables, but
square brackets (
[]
) are added:
int x; // declares variable x int[] arr; // declares array arr
⦿
Note that the type of the array’s element must
be declared with the array (just like a variable)
◼ This type cannot change
ARRAYS
⦿ Arrays can be initialized in two ways:
⦿ Direct initialization:
int[] intArr = {1, 2, 3, 4, 5}; String[] strArr = {"Welcome", "to", "AP", "CS"}; double[] doubleArr = {};
◼ Size is inferred
◼ Initial value of elements are provided
⦿With a constructor:
int[] intArr = new int[5];
String[] strArr = new String[4]; double[] doubleArr = new double[n];
◼Size is given explicitly (variable or literal of any integer type)
ARRAYS
⦿
The size of an array cannot change once it has been
initialized
◼ However, you can assign a new array of a different size to the same array variable:
int[] arr = new int[6]; ...
arr = new int[8];
◼ When you do this, the elements are not copied over This is a rare thing to do
⦿
The size of an array can be found by using the
length
field:
ARRAYS
⦿
Elements of an array are accessed using an
indexer:
int[] primes = new int[3];
primes[0] = 2;
primes[1] = 3;
primes[2] = 5;
⦿
Notice that indexing begins at zero!
◼
What is the largest valid index of an array
arr
?
OBJECTS
⦿
Recall that only some Java types are
primitive types
◼
int
,
char
,
boolean
, etc.
⦿
Most types in Java are object types
⦿
An object is an entity that encapsulates
related data and behavior
REFERENCES
⦿
Technically, things like
System.out
are not
objects. They are references to an object:
⦿
The actual object lives in memory
somewhere
Some PrintStream
object
REFERENCES
⦿ This means we can declare our own variable and have it refer to the same object as System.out
PrintStream myStream; myStream = System.out;
⦿ Note that this does not create a new object, just a new reference
Some PrintStream
object
System.out
REFERENCES
⦿ A similar example, using the String class:
String firstString = "Java";
String secondString = firstString;
⦿ In Java, each string has a unique object that represents it:
String firstString = "Java"; String secondString = "Java";
The string “Java”
firstString
ARRAY REFERENCES
⦿
Arrays are also references, so we can have
two references to the same array:
int[] arr1 = new int[4];
int[] arr2 = arr1;
⦿
Since both references are to the same array,
both will see changes to the elements!
arr1ARRAYS
⦿ Exercise 1: Write a Java program to ask the user for a
number, then simulate rolling a die that number of times, and output how many times each number (1 through 6) was rolled. Use an array!
⦿ Exercise 2: Repeat Exercise 1 rolling a pair of dice and tracking the total of the pair. Use an array!
⦿ Exercise 3: Write a Java program to read a string from the user then count and print out the number of times each letter A-Z appears in the string.
◼ You may assume all letters in the string are lowercase, but DO
ARRAYS
⦿ Exercise 4: Write a Java method that takes an array of Strings as an argument, and returns an array containing the number of vowels in each String.
⦿ Exercise 5: Write a Java method that takes an array of numbers as an argument and then prints out the sum of each consecutive pair.
◼ For example, if the argument is:
[3, 7, 12, 9, -5, 0, 3] the output would be:
10 19 21 4 -5 3
ARRAYS
⦿
Exercise 6: Write a Java method that takes in an
array of numbers, then determines whether or
not the numbers were given in sorted order.
Your method should return true if the numbers
were input in
increasing
order and false if not.
⦿
Bonus: Modify the method to return true if the
numbers were given in
either
increasing
or
MULTI-DIMENSIONAL ARRAYS
⦿
The arrays we have worked with so far are called
single-dimensional arrays
⦿
We can also have multi-dimensional arrays:
int[][] twoDimArray = new int[5][7]; int[][] otherArray = { { 1, 2, 3 }, { 4, 5, 6 } };
⦿
Essentially, each element of the outer array is
another array:
TWO-DIMENSIONAL ARRAYS
⦿
You can think of a two-dimensional array as a
table or matrix:
int[][] twoDimArr = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
NESTED LOOPS
⦿
Just like for loops work well with arrays,
two-dimensional arrays and nested loops go
hand-in-hand:
String[][] twoDimArr = new String[3][5]; ...
for (int i = 0; i < twoDimArr.length; i++) {
for (int j = 0; j < twoDimArr[i].length; j++) { System.out.print(twoDimArr[i][j] + " "); }
MULTI-DIMENSIONAL ARRAYS
⦿ Exercise 1: Write a program to simulate rolling two
six-sided dice a given number of times (specified by the user) and print out how many times each possible set of results was rolled. Track both dice separately (i.e. 1-4 is a different result than 2-3 even though they both add up to 5).
⦿ Exercise 2: Write a program asking the user to input a
number of words, then print out the number of time each vowel occurs in each string (tracked separately). For
example, if the words input were "cat", "watermelon"
and "cheese", then the output would be: 1-0-0-0-0,
COMMON LOOP/ARRAY BUGS
⦿
Infinite Loop:
// read in Strings and output them in uppercase
Scanner kb ...;
String input = kb.nextLine(); while (!input.equals(“quit”)) {
COMMON LOOP/ARRAY BUGS
⦿
Infinite Loop:
// read in Strings and output them in uppercase
Scanner kb ...;
String input = kb.nextLine(); while (!input.equals(“quit”)) {
System.out.println(input.toUpperCase());
input = kb.nextLine();
COMMON LOOP/ARRAY BUGS
⦿
Fencepost bug:
// Print out comma-separated list of ints 1-10
for (int i = 0; i < 10; i++) {
System.out.print((i + 1) + “, “); }
COMMON LOOP/ARRAY BUGS
⦿
Fencepost bug:
// Print out comma-separated list of ints 1-10 int i;
for (i = 0; i < 9; i++) {
System.out.print((i + 1) + “, “); }
System.out.println((i + 1));
COMMON LOOP/ARRAY BUGS
⦿
Array overrun:
// read 10 integers into an array
Scanner kb ...;
int[] arr = new int[10];
for (int i = 0; i <= 10; i++) {
arr[i] = kb.nextInt();
COMMON LOOP/ARRAY BUGS
⦿
Array overrun:
// read 10 integers into an array
Scanner kb ...;
int[] arr = new int[10];
for (int i = 0;
i < 10
; i++) {
arr[i] = kb.nextInt();
COMMON LOOP/ARRAY BUGS
⦿
Off-by-one bug:
// track die rolls
int[] rolls = new int[6];
for (int i = 0; i < n; i++) {
int rand = (int)(Math.random() * 6 + 1);
rolls[rand]++;
COMMON LOOP/ARRAY BUGS
⦿