Introducing 

Prezi AI.

Your new presentation assistant.

Refine, enhance, and tailor your content, source relevant images, and edit visuals quicker than ever before.

Loading…
Transcript

Lesson 4.6

Do Now

what if they aren't sequential?

what if you don't know how many there will be?

index 0

an array filled with String[]'s

{"George", "John", "Thomas", "James"}

int[] names = {"Tommy", "Chucky", "Angelica", "Jessica"}

"Jefferson"

print out pairs of first and last names from the two arrays inside the two-dimensional array

for(int i = 0; i < names.length; i++)

{

if (names[i] == "Jessica")

System.out.println("We missed her yesterday!");

else

System.out.println(names[i] + " is cool!");

}

{ {"","",""}, {"","",""}, {"","",""} }

String

creates a two-dimensional array of empty Strings (""'s)

{"","",""}

{"","",""}

{"","",""}

//nested loops!

names[0] -> "Tommy"

{"","","O"}

{"","X",""}

{"","X",""}

1

for(int i = 0; i < names.length; i++)

{

for(int j = 0; j < stooges.length; j++)

{

if(names[i] == stooges[j])

System.out.println("A match!")

}

}

1

is names[0] == stooges[0]?

is names[0] == stooges[1]?

is names[0] == stooges[2]?

1

Quick Review: Create an array with 4 Strings in it. How would you print out the 1st letter of each of these Strings?

myInt6 = 31;

myInt7 = 5;

myInt8 = 77;

...

myIntN = ?;

We will share out answers during the last 5 minutes!

HW: two practice questions on coding bat (printed out for you)

String[] myStrings = {"Hi", "Hello", "Howdy", "Yo"};

for(int i = 0; i < myStrings.length; i++)

We need a way to deal with collections of data, because you don't always know what information, or how much information, will be used in your programs!

System.out.println(myStrings[i].substring[0,1]);

A class needs to define what fields an object can share, and what fields can be modified.

Aim & Challenge

//assume Vehicle is already defined

//should return 10000

Vehicle standardCar = new Vehicle ()

standardCar.getPrice();

standardCar.setPrice(5);

standardCar.getPrice();

AIM: SWBAT review correct solutions to the Arrays quiz and continue reviewing Java Classes in Chapter 10.

//should change the price

//should return 5

Product: Bronze/Silver

Unit 2 Test Make-Up

Codingbat.com/java

HW: Be ready to finish the methods tomorrow!

- make an account

- prefs --> share to jeiben@kippnyc.org

- complete challenges based on topics that you missed

notice this test class uses the renewContract() method from the Player class!

Your constructors should have parameters that are in the same order as in these objects in the test class!

Logistics

these data types were specified in the TestPlayer description

this class still needs all of the field values from Player!

this uses the constructor from Player

not required, but it can make the if's easier to read

same as if(leftHanded == true)

int/int = int

?

double/int = double

or, make a variable that is equal to (double)hits/atBats

equivalent to:

if(!(injured || salary > 100000*cost)

Tomorrow a similar practice assignment will be available if you want to get recovery credit for the written portion of the exam.

- Unit 3 Test corrections due Weds

Mon - Array notes

Tues - Two-Dimensional Arrays

Weds - Array Practice

Thurs - Lab: MadLibs

Fri - Quiz: Arrays

Mr. Eiben will be out of town. Don't cry!

Agenda

Test Results

Recovery

Ch. 3 # 1, 2, 3, 5, 6

-

+

Unit 1 Test Corrections

Focus on the question types that you struggled on! If you want more practice, check out codingbat.com/java and do the strings 1 challenges!

String methods

Simple loops

complex loops

creating own methods

For each question you missed...

1) Identify the topic or skill that you struggled with

2) Find a practice question from the textbook that addresses this topic or skill

3) Answer the question

4) Explain how this practice question helps you to understand the skill or topic better

I. Do Now

II. Quiz Solutions

III. Partner Work - Ch. 10

average: 32, out of 40

Review - Ch. 4

What topics do we need help mastering?

- instances of a Class

- private & public fields

- calling methods

- object.someMethod()

- inheritance

- extends, superclass

- Classes

- Fields

- Constructors

- no-args & with-args

- methods

- getter & setter

Full Class

LoopExercises.java

8

"home"

"me"

"run"

int p = s.indexOf(w);

4

//where is w?

Review:

- For Loops

- While Loops

int len = w.length();

//how long is w?

String stars = len*("*");

//how many *'s?

String front = s.substring(0,w);

//front

String back = s.substring(w+len);

//back

System.out.println(front+stars+back);

Today I had a

sandwich for lunch!

***

0

17

14

true

xWord()

pygLatin()

false

true

false

1

false

true

1

false!

.equals()

s1 and s2 are stored in different locations in the memory, so they are not equal!

Partner

- uploaded file on GC

- load into eclipse

- write the methods

- run the file to test the methods

"The shoes cost 125"

if your birthday has already come, your age is the yearToday - birth year

"125"

11

if your birthday hasn't already come, your age is the yearToday - birth year -1

13

2015

int age;

if (month < monthToday)

age = yearToday - year;

if (month > monthToday)

age = (yearToday - year - 1);

247 (integer)

if (month == monthToday)

{

if (day <= dayToday)

age = yearToday - year;

else

age = yearToday - year -1;

}

return age;

how could we print out a statement explaining the age of a person with the given month, day and year?

System.out.printf("A person born on

%02d/%02d/%d is %d years old!",

month, day, year, age);

"1.70"

"A person born on 01/17/1986 is 29 years old!"

"01"

"17"

Independent

Arrays Quiz Recovery Credit

II. Lesson

Creating New Arrays

write a method that returns a capitalized name (assuming the name is a String)

String Methods

Strings

Arrays

int[] myNums = new int[6];

- practice questions will be on Google Classroom by tomorrow

- finish recovery assignments before winter break!

array name

an array of up to 6 ints

sets the type

String x = "pumpkin";

two methods...

1) 'new' constructor

2) use { ... }

assigning values to the array positions

myNums[0] = 4;

myNums[1] = 9;

myNums[6] = 1;

Once an array is created, you can't change the length of the array!

0 1 2 3 4 5 6

3.2 - More Loops

3.1

causes an out of bounds error!

public static String capitalize(String n)

{

}

return (n.charAt(0) + n.subString(1));

are 'immutable' - once you create a new string object and give it a value, you can't change that value.

If you want to add values beyond that initial size, you need to create a new array, copy the contents of the original into it, and then add new values where you have space!

7

String[] names = {"Mia", "Fred", "Alondra"};

String[] words = {"me", "my", "I"};

an array of up to 3 ints

array name

sets the type

4

words[1]; //equals "my"

words[4]; //out of bounds error

int[] nums = {4, 18, 99, 103};

Type casting

x.length()-1

initialization

Ch. 5 Topics

both of these lines create a new String object, s

- a built-in class in Java, can hold multiple pieces of data

- have their own methods and fields (like any other class)

n

k

condition

this would print...

you can replace a value in an array with another value (of the same type!)

change

capitalize("skippy") should return "Skippy"

1 banana...

2 banana...

3 banana...

4 banana...

5 banana...

double[] dubs = new double[5];

words[2] = "hers";

System.out.print(words[2]);

2

String s = "turkey";

x.length();

x.charAt(position); //count starts at 0

x.subString(fromPosition);

x.subString(fromPosition, toPosition);

x.concat(string);

Boolean expressions

Chapter 7 #1, 2, 6

Loops

initialization

condition

change

Algorithm

These mean the same thing. The String class has a special constructor that lets you skip the 'new' call

mpkin

included, not included

String s = new String("turkey");

Practice with Arrays

this would print...

write a method that takes in a string and returns a string that capitalizes the letter following the last instance of the letter 'e'

findPotato()

What an odd number!

2

What an odd number!

4

...

1

4

(type)object turns the object into that type, if possible

HW: Ch. 7 # 7

A step-by-step process for processing information

ump

1) Create an array of strings with 5 values, each representing a food.

2) Write a method that iterates through the array and checks if any of the values equals "potato" and returns true if "potato" is in the list, otherwise it should return false.

Allow you to re-use portions of code multiple times in a row.

10

4

If you wanted to change the value of s, you would need to overwrite it with a new complete string.

pattern1(3)

n = 3

'kipp college prep'

pumpkin pie

3

4

" pie"

randAvg()

names.length;

finds the length field of the names array --> 3

14

4

k=3

k=4

'kipp college pre'

public static String capAfterE(String n)

{

}

10

nums[1];

1) Create an empty array of ints that is 10 values long.

2) Write a loop that chooses a random number between 1 and 10, and stores that number in the list you created.

3) Write a loop that iterates through your list to find the average int.

Generally, people think about algorithms as a set of rules that you can REPEAT to reach a goal.

finds the item in the nums array at index 1 --> 18

'P'

n = n.toLowerCase();

int lastE = n.lastIndexOf('e');

String front = n.subString(0, lastP +1);

char swap = n.charAt(lastP + 1).toUpperCase();

String back = n.subString(lastP +1);

return front + swap + back

1

4

19

22

46

94

...

pumpkin

0

System.out.print(x);

s = "mashed potatoes";

''

int/int returns an int (.3 gets rounded down to nearest int, 0)

This can make your code shorter, and easier to edit or update in the future.

dubs[0] = 3.14;

sets the 0 index of dubs to 3.14

if ( condition )

{

//do something

}

just in case the last e isn't the 2nd to last letter...

int count = 3;

int total = 10;

count / total =

(double)(count / total) =

(double)(count)/total =

rollCount()

Local Variables, Fields & Parameters

Escape characters

Basic arithmetic (order of operations)

Integer division

Modulo (%)

Now s refers to a new location in the computer memory, storing a new string

1) Create an array of 6 zeroes (0).

2) Write a loop that simulates rolling one die 100 times and keeps track of how many times each possible value is 'rolled'

3) After the loop has run, what do you expect to see if you print your array?

capAfterE("kipp college prep") should return "kipp college preP"

using the .concat() method does not change the value of x, because strings are immutable!

0.0

bigEven(int n)

'kipp college pre'

initialization

should return the smallest even number that is larger than the input integer, n

Find the pattern and write a method to find the nth term in this sequence:

condition

using a while loop!

this executes first, returning 0

all 3 are needed to avoid an error or infinite loop!

change

Chapter 3: Syntax & Style

Chapter 5: Data & Arithmetic

1, 0, 2, -2, 6, -10, 22, -42, 86

//should print 5

Since Strings are immutable, none of the methods that the String class provides actually change the value of the String:

.3

Practice:

public int pattern2(int n)

{...}

bigEven(int n)

condition

change

initialization

should return the smallest even number that is larger than the input integer, n

using a for loop!

3.0 / 10 = .3

// should print 1

2

3

initialization

bigEven(int n)

String y = "Thanksgiving";

xWord(String w)

{

}

should return the smallest even number that is larger than the input integer, n

write a method factor3Or5(int n) that returns true if 3 OR 5 is a factor of n. (hint: %)

using a do-while loop!

0 1 2 3 45 67891011

change

//should print 7

6

5

4

'i'

condition

String s = "mashed potatoes";

System.out.print( s.toUpperCase() );

System.out.print( s );

7

factor3Or5(7) --> false

factor3Or5(9) --> true

factor3Or5(15) --> false

MASHED POTATOES

'overloaded' method has more than one set of input structures

- reserved words

- capitalization

- indentation

- ;'s, { } 's, etc

- local, public, and instance variables

- data types (primitives & classes)

- Arithmetic (order of operations, %, integer division, etc)

'i'

8

Boolean operators

Compound Operators

9

mashed potatoes

y.indexOf(character);

y.indexOf(character, position)

y.lastIndexOf(character);

y.lastIndexOf(String);

'n'

How can we change the value of a string?

10

this is the 'AND' operator

"sgi"

there are overloaded versions of lastIndexOf()

if ( condition1 && condition 2 )

{

}

s = s.toUpperCase();

System.out.print(s);

5

evaluates as 'true' only if BOTH conditions are true.

...

double n = 16.5;

n = n + 1;

n :

double q = 1.72;

q += 1;

q :

MASHED POTATOES

( 7>6 ) && ( 1 == 1 )

true

false

( 6/3 > 4/2 ) && ( 7+3 == 10 )

same as q = q + 1

(( 7>6 ) && ( 1 == 1 )) &&

(( 6/3 > 4/2 ) && ( 7+3 == 10 ))

Chapter 4: Classes & Objects

Chapter 6: Conditional Logic

String z = "Food Coma";

false

17.5

2.72

"FoodComa"

2.1

2.2

+= -= *= /= %=

'o'

'q'

this is the 'OR' operator

if ( condition1 || condition 2 )

{

}

"Fqqd Cqma"

...

z.trim();

z.replace(oldChar, newChar)

z.toUpperCase();

z.toLowerCase();

evaluates as 'true' only if ONE condition is true.

- fields, constructors & methods

- Inheritance

- Creating objects & calling methods

- boolean expressions & operators

- if/else statements

- nested if/else statements

"FOOD COMA"

( 7>6 ) || ( 1 == 1 )

false

true

( 6/3 > 4/2 ) || ( 7+3 == 10 )

"food coma"

Increment / Decrement

(( 7>6 ) && ( 1 == 1 )) ||

(( 6/3 > 4/2 ) && ( 7+3 == 10 ))

true

Nested 'blocks'

11 - (1 + 9)

What is the difference?

int j = 10;

j--;

j :

int i = 10;

i++;

i :

1

i += 1 j -= 1

Java Syntax

Java Style

i -= ++j;

i :

i -= j++;

i:

this is the 'NOT' operator

if ( !condition1 )

{

}

Naming Things

Comments

9

11

Name things logically

demo

multi-line comment

...

evaluates as the opposite of the boolean value for the term

// age variable

Class names must start with a capital letter.

variables & methods start with lowercase letters

int a = 18;

int age =18;

int thisIsMyAge = 18;

/* Use comments to explain HOW your code works! This will keep you organized, especially if you take a break from the project and come back to it later. It also helps other coders to work with you */

Javadoc comment

/* ... */

/**... */

//

(11 - 9) + 1

error - reserved word!

int int = 4;

Multi-word names = CamelCase

single-line comment

(!true)

false

Practice: Chapter 6 #'s

Objects usually named as nounse, Methods usually named as verbs

true

( !(true)|| ( 7+3 == 10 )

Reserved Words

Structural Rules

Indent blocks of code uniformly. This will help you to keep track of what statements belong to which classes, objects, or methods.

Code Structure

All statements end in with ";"

Have a pre-set, unchaneable meaning in Java. Don't use these as names for your own variables or methods:

Include author & purpose of code

The AP test structures brackets this way, so you should too!

3

packagaes like java.util.Scanner

public class JobInterview

char, int, double (all data types), true, false, null, public, private, protected, static, final, if, else, for, while, do, break, return, new, this

class JobInterview

{

public static void main (String[] args)

{

String myName = "Mr. Eiben";

System.out.println(myName);

}

}

( !(7>6) && (1 == 1)) ||

( !( 6/3 > 4/2 ) && ( 7+3 == 10 ))

class JobInterview

{

public static void main (String[] args)

{

String myName = "Mr. Eiben";

System.out.println(myName);

}

}

1) Comment

2) Imports

3) Class Header

4) Class Body:

- Fields

- Constructors

- Methods

create and/or define class variables

true

this 'white space' is ignored by the Java compiler, but it makes it easier for people to read your code!

Plus many more. Eclipse usually color codes these for you!

create objects

'blocks' of code are contained by { }

the things your class can DO

2, 3, 4, 7, 15

De Morgan's Laws

switch statements

can be useful for situations where there are many 'ifs' that you want to check for

!(P && Q) = !P || !Q

!((z <= 5) && (z > 3)) =

String month;

if (answer == 1)

{

month = "January";

}

if (answer == 2)

{

month = "February";

}

... //more if statements

String month;

switch (answer) {

case 1: month = "January";

break;

case 2: month = "February";

break;

...

case 12: month = "December";

break;

}

!(z <= 5) || !(z > 3)

true when z is in the range:

(-infinity, 3] (5, infinity)

this is the same as writing an if/else if/else if/else block!

(z > 5) || (z <= 3)

switch (condition) {

case value1: //do something;

break;

case value2: //do something;

break;

case value3: //do something;

break;

default: //do something;

break;

}

!(R || S) = !R && !S

!((z == 6) || (z < 4)) =

the reserved word 'break' stops the remaining switch conditions from being checked. It is optional, but often useful.

true when z is in the range:

[4, 6) (6, infinity)

!(z == 6) && !(z < 4)

(z != 6) && (z >= 4)

III. Today's Challenge

Unit 2 Test Review

GradeCalculator

Equation for total grade for classes with category weights:

HW = 20%, Quizzes = 30%, Tests = 50%

Suggestions:

1) Review notes and classes in Eclipse

2) Try exercises in the text

3) http://codingbat.com/java

(120 / 200) * 20 = 12

be careful with ints and doubles!

(HW proportion * 20)

(70 / 150) * 30 = 14

+

(Quiz proportion * 30)

totalGrade =

(95 / 100) * 50 = 47.5

+

73.5

Bronze - Complete the short

answer questions about the

Fraction class.

Silver - Start to write the methods on the practice sheet.

Gold - open the Fractions class in the JavaMethods folder, chapter 10, in Eclipse. Add your methods and test them!

(Test proportion * 50)

online practice questions

IV. Home Work

Java Methods Chapter 1

read, annotate, and complete Google Classroom response survey (can be done on your phone if you download app!)

Learn more about creating dynamic, engaging presentations with Prezi