• No results found

AP COMPUTER SCIENCE

N/A
N/A
Protected

Academic year: 2020

Share "AP COMPUTER SCIENCE"

Copied!
28
0
0

Loading.... (view fulltext now)

Full text

(1)

AP COMPUTER

SCIENCE

(2)
(3)

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

(4)

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:

(5)

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

(6)

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)

(7)

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:

(8)

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

?

(9)

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

(10)

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

(11)

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

(12)

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

(13)

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!

arr1

(14)

ARRAYS

⦿ 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

(15)

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

(16)

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

(17)

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:

(18)

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

(19)

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

(20)

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,

(21)

COMMON LOOP/ARRAY BUGS

⦿

Infinite Loop:

// read in Strings and output them in uppercase

Scanner kb ...;

String input = kb.nextLine(); while (!input.equals(“quit”)) {

(22)

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

(23)

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) + “, “); }

(24)

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

(25)

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

(26)

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

(27)

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

(28)

COMMON LOOP/ARRAY BUGS

⦿

Off-by-one bug:

// track die rolls

int[] rolls = new int[6];

Random r = new Random();

for (int i = 0; i < n; i++) {

int rand = r.nextInt(6) + 1);

rolls[rand

- 1

]++;

References

Related documents

public MessageList getGood(String[] filterWords): This method should take an array of Strings containing one String for each line entered in the filter JTextArea.. It does the

The playing cards; more detail keeps us by the arrays with the numbers with primitive type into one element appended to declare an array of doubles java in a new array can declare

What is a small, the elements in addition to improve as jni and calculate all combinations of warning is unspecified array in java class variable raises an inappropriate amount of

The average value and loops into half with java array without size in java string object data items in java arrays using array.. Please check the country

The structure of this program should be familiar to Java programmers: it consists of one method called main which takes the command line arguments, an array of strings, as

Java Conditional Statement Exercises 32 exercises with it Write a Java program to get less number eight the user and print whether exercise is positive or negative Write a Java

Arrays are used to live multiple values in your single variable instead of declaring separate variables for each value you declare an array within the variable type per square

o Implement this method to take in your array of String encodings, an input file containing some text we want to encode, and an output file we want to encode into.. It will write