Control & Arrays 15-121 Fall 2020 Margaret Reid-Miller Today - - PowerPoint PPT Presentation

control arrays
SMART_READER_LITE
LIVE PREVIEW

Control & Arrays 15-121 Fall 2020 Margaret Reid-Miller Today - - PowerPoint PPT Presentation

Control & Arrays 15-121 Fall 2020 Margaret Reid-Miller Today No in class Quiz. Quiz will be asynchronous. Strings continued Java naming conventions Flow Control: conditionals, loops, scope Arrays Fall 2020 15-121


slide-1
SLIDE 1

Control & Arrays

15-121 Fall 2020 Margaret Reid-Miller

slide-2
SLIDE 2

Today

  • No in class Quiz. Quiz will be asynchronous.
  • Strings continued
  • Java naming conventions
  • Flow Control: conditionals, loops, scope
  • Arrays

Fall 2020 15-121 (Reid-Miller) 2

slide-3
SLIDE 3

Basic types

What is the difference between a char and a String variable? char is a primitive type for a single character. String is an object type for a sequence of characters. How are char and String literals different? char uses a pair of single quotes (e.g., 'x'). String uses a pair of double quotes (e.g., "x"). What is the difference between a null String and an empty String? null is when a String variable is undefined. an empty no has characters in it (i.e., "").

Fall 2020 15-121 (Reid-Miller) 3

slide-4
SLIDE 4

Python vs Java

How does LetterCounter1.java compare to LetterCounter1.py? In Java

  • Must declare types of variables
  • To read input, need a Scanner object
  • Statements terminated with ;
  • Uses {} to delimit blocks of code
  • Cannot use list(array) indexing on Strings
  • for loops are different

Fall 2020 15-121 (Reid-Miller) 4

slide-5
SLIDE 5

Fall 2020 15-121 (Reid-Miller) 5

Identifiers and Keywords

  • Identifiers are names that specify different elements
  • f a program such as class, method, or variable
  • can be any combination of letters, digits, _ or $
  • the first character must NOT be a digit
  • case-sensitive (total is different from Total)

Examples: main method1 maxCount TUESDAY $amount Puzzle

  • Keywords are a set of predefined identifiers that are

reserved for special uses. Examples: public static void class

slide-6
SLIDE 6

Fall 2020 15-121 (Reid-Miller) 6

Java naming conventions readily distinguish various Java elements

  • Class: Starts with a capital letter, same name as file name
  • A class names should be a noun that describe an
  • bject type.

e.g., String, Dice, Radio

  • Method: Starts with a lower case letter, camelCase
  • A method name should start with a verb and

describe what the method does. e.g., displayQuestion, getName, computeTax

slide-7
SLIDE 7

Fall 2020 15-121 (Reid-Miller) 7

Java Naming Conventions (cont’d)

  • Variable: Starts with a lower case letter, camelCase
  • A variable name should be a noun that describes

what data it holds. e.g., favoriteFood, name

  • Constant: All upper case with underscores
  • Constants are declared with the keyword final
  • A constant name should be a noun that describes

what data it holds. e.g., PI, TAX_RATE

slide-8
SLIDE 8

Flow Control

Conditionals, Loops, Scope

slide-9
SLIDE 9

Fall 2020 15-121 (Reid-Miller) 9

Conditionals

if (boolean_expression) statement if (boolean_expression) statement1 else statement2

A statement can be any Java statement:

  • A simple statement
  • A compound statement, such as an if statement
  • A block statement, a group of statements enclosed in

braces {}

slide-10
SLIDE 10

Fall 2020 15-121 (Reid-Miller) 10

The Dangling else Problem

  • When an if statement is nested inside an if clause,

its else clause is paired with the closest if statement that does not have an else clause.

if (x > 0) if (y > 0) color = “red”; else color = “blue”;

Misleading indentation Recall: Indentation is not semantic!

slide-11
SLIDE 11

Fall 2020 15-121 (Reid-Miller) 11

Each else is paired with closest if that has no else

  • In reality it is

if (x > 0) if (y > 0) color = “red”; else color = “blue”; y x y x

slide-12
SLIDE 12

Fall 2020 15-121 (Reid-Miller) 12

Always use {} with if statements

  • Use braces to pair else

with the outer if

if (x > 0) { if (y > 0) color = “red”; } else { color = “blue”; } y x

(if or else on a single line without braces is OK.)

slide-13
SLIDE 13

Fall 2020 15-121 (Reid-Miller) 13

Multiple Alternatives

  • Determine if a number is positive, negative, or zero:

if (value < 0) { System.out.println(“Value is negative.”); } else if (value == 0) { System.out.println(“Value is zero.”); } else if (value > 0) { // Redundant test! System.out.println(“Value is positive.”); } At most one statement is executed. Each choice, however, is at same indentation.

slide-14
SLIDE 14

Fall 2020 15-121 (Reid-Miller) 14

Multiple Alternatives

  • Determine if a number is positive, negative, or zero:

if (value < 0) { System.out.println(“Value is negative.”); } else if (value == 0) { System.out.println(“Value is zero.”); } else { // value must be positive System.out.println(“Value is positive.”); } It is clear, exactly one statement is executed.

slide-15
SLIDE 15

Fall 2020 15-121 (Reid-Miller) 15

The switch statement

  • If an if/else statement with multiple alternatives

compares an int or char expression against several constants you can use a switch statement. Example:

switch (suitAsChar) { case ‘C’: suitAsName = “Clubs”; break; case ‘D’: suitAsName = “Diamonds”; break; case ‘H’: suitAsName = “Hearts”; break; case ‘S’: suitAsName = “Spades”; break; default: suitAsName = “Unknown”; }

  • WARNING: You must include break to avoid executing the

the body of the following case!

slide-16
SLIDE 16

Fall 2020 15-121 (Reid-Miller) 16

Java has 3 kinds of Loops

initialize while (test) { do_stuff update } for (initialize; test; update) { do_stuff } initialize do { do_stuff update } while (test);

Note: do-statement executes loop at least

  • nce – not often used
slide-17
SLIDE 17

While Loop

int i = 0; while (i < n) { System.out.print(“*”); i++; } System.out.println();

Fall 2020 15-121 (Reid-Miller) 17

slide-18
SLIDE 18

for Loop

for (int i = 0; i < n; i++) { System.out.print(“*”); } System.out.println();

Fall 2020 15-121 (Reid-Miller) 18

slide-19
SLIDE 19

Fall 2020 15-121 (Reid-Miller) 19

Scope

  • The scope of a variable is the area within a program

that can reference the variable.

  • The scope depends on where the variable is

declared.

int sum = 0;

for (int i = 1; i <= n; i++) { sum += i*i; }

System.out.println(sum);

Scope of variable i

slide-20
SLIDE 20

Fall 2020 15-121 (Reid-Miller) 20

Scope

int sum = 0; int i;

for (i = 1; i <= n; i++) { sum += i*i; }

System.out.println(“Sum of first “ + (i-1) + “ integers squared is “ + sum); }

Scope of variable i ends at the enclosing brace

slide-21
SLIDE 21

Fall 2020 15-121 (Reid-Miller)

Use a do-while if you must execute the body of the loop at least once.

Scanner console = new Scanner(System.in); int month; do { System.out.print( “Please enter the month [1-12]: ”); month = console.nextInt(); } while ( ); month < 1 || month > 12 Must be declared

  • utside the loop

Outside the scope

  • f the loop

21

slide-22
SLIDE 22

Arrays

slide-23
SLIDE 23
  • How do we say/pronounce this?

int[]

  • What is poor about this code?

int[] count;

  • What does this code do?

int[] counts;

  • How do I create an array?

Fall 2020 15-121 (Reid-Miller) 23

Array of int or int Array Use plural names Declares counts to refer to an array of ints (but doesn’t yet) new [ ] type how many

Java arrays use special syntax

slide-24
SLIDE 24
  • Declare and create:

int[] counts; counts = new int[6];

  • Shortcut:
  • Arrays are automatically filled with default

values when created:

  • int[], double[], char[] is
  • boolean[] is
  • String[] is

Fall 2020 15-121 (Reid-Miller) 24

int[] counts = new int[6]; false null (as with all objects)

Creating an array

must match

slide-25
SLIDE 25

Fall 2020

Initializer List

  • You can declare, create, and initialize an array with a

list of values or expressions. int[] counts = {12, 22, 17, 16, 4, 11};

  • You can use an initializer list only when the array is

first declared.

  • Each value must match the type of the array.
  • The values go into the array in the order given and

determine the length of the array.

25 15-121 (Reid-Miller)

slide-26
SLIDE 26

Fall 2020

Arrays are uniform, fixed length, and have no methods

  • Every element of an array must be the same type.
  • We will see how to get around that restriction later
  • You can make arrays of primitives values or objects.
  • The length of an array is determined when it is first

created and cannot grow or shrink

E.g., counts.length

  • Unlike Python, there is no slicing (e.g., arr[2:5])

and no negative indices (e.g., arr[-1]).

26 15-121 (Reid-Miller)

Note no ()! It’s a value, not a method.

slide-27
SLIDE 27

Array Demo

Fall 2020 15-121 (Reid-Miller) 27

slide-28
SLIDE 28

Fall 2020

  • When you copy an array variable x to a variable y, you

copy the reference not the values in the array.

int[] x = {1, 3, 7, -4, 2, 8, 5, 0, 4, 6} int[] y = x

  • Changes made to x or y are seen by both variables.
  • We say x and y are aliases (two names for the same

array)

Aliasing

x

f2e23 f2e23

28 15-121 (Reid-Miller)

y f2e23

1 3 7

  • 4

2 8 5 4 6

slide-29
SLIDE 29

Pass by Value

  • When you call a method with an argument, the

method parameter variable receives a copy of the argument value.

  • The argument and parameter variables are in

different scopes.

  • When the method returns, what happens to the

parameter variable?

  • It is destroyed. Recall the scope (end-of-the-life)
  • f a variable.
  • What is copied when the argument is an array?
  • The reference to the array.

Fall 2020 15-121 (Reid-Miller) 29

slide-30
SLIDE 30

Fall 2020

int[] values = new int[10]; fillAllSums(values); public static void fillAllSums(int[] vals) { vals[0] = 0; for (int i = 1; i < vals.length; i++) { vals[i] = vals[i-1] + i; } }

Arrays as Parameters

values

ae2f3 ae2f3

30 15-121 (Reid-Miller)

In main, for example

slide-31
SLIDE 31

Fall 2020

int[] values = new int[10]; fillAllSums(values); public static void fillAllSums(int[] vals) { vals[0] = 0; for (int i = 1; i < vals.length; i++) { vals[i] = vals[i-1] + i; } }

The array reference is copied to the parameter

values

ae2f3 ae2f3

31 15-121 (Reid-Miller)

vals ae2f3

slide-32
SLIDE 32

int[] values = new int[10]; fillAllSums(values); public static void fillAllSums(int[] vals) { vals[0] = 0; for (int i = 1; i < vals.length; i++) { vals[i] = vals[i-1] + i; } }

1 3 6 10 15 21 28 36 45

Fall 2020

An array parameter is an alias

values

ae2f3 ae2f3

32 15-121 (Reid-Miller)

vals ae2f3

slide-33
SLIDE 33

1 3 6 10 15 21 28 36 45

Fall 2020

int[] values = new int[10]; fillAllSums(values); public static void fillAllSums(int[] vals) { vals[0] = 0; for (int i = 1; i < vals.length; i++) { vals[i] = vals[i-1] + i; } }

Changes to an array in a method are visible outside the method!

values

ae2f3 ae2f3

33 15-121 (Reid-Miller)

slide-34
SLIDE 34

Returning an Array

Fall 2020 34 15-121 (Reid-Miller)

int[] values = getAllSums( 8 ); … } public static int[] getAllSums(int n) { int[] vals = new int[n]; vals[0] = 0; for (int i = 1; i < n; i++) { vals[i] = vals[i-1] + i; } return vals; }

slide-35
SLIDE 35

What happens when we swap values?

Fall 2020 15-121 (Reid-Miller) 35

slide-36
SLIDE 36

An array variable holds null if no array is created (distinct from an array with 0 elements.)

int array[] counts; public static int[] copy(int[] data){ int[] data2 = new int[data.length]; for (int i = 0; i < data.length; i++){ data2[i] = data[i]; } return data2; }

The null reference

Fall 2020

counts null

Causes a nullPointerException if data is null

36 15-121 (Reid-Miller)

slide-37
SLIDE 37

public static int[] copy(int[] data){ if (data == null) return null; int[] data2 = new int[data.length]; for (int i = 0; i < data.length; i++){ data2[i] = data[i]; } return data2; }

Be sure to test for null!

Fall 2020 37 15-121 (Reid-Miller)

slide-38
SLIDE 38

Arrays class (part 1)

What happens if we just print an array variable (using toString)? Some useful methods from java.util.Arrays

  • Arrays.toString(arr)
  • Arrays.equals(arr1, arr2);
  • Arrays.sort(arr)

Fall 2020 15-121 (Reid-Miller) 38