Strings Final Project Example How would you make this? Take a - - PowerPoint PPT Presentation

strings
SMART_READER_LITE
LIVE PREVIEW

Strings Final Project Example How would you make this? Take a - - PowerPoint PPT Presentation

Strings Final Project Example How would you make this? Take a deep breath Final Project Example public class SpaceInvaders extends GraphicsProgram { private ArrayList<GOval> aliens; private GRect paddle; public void run() { Setup


slide-1
SLIDE 1

Strings

slide-2
SLIDE 2

Final Project Example

🤕

How would you make this? Take a deep breath…

slide-3
SLIDE 3

public class SpaceInvaders extends GraphicsProgram { private ArrayList<GOval> aliens; private GRect paddle; public void run() { // create objects and scores // add() to canvas setupGame(); while(!gameOver()) { animateObjects(); pause(100); } } private boolean keyPressed() {...} private boolean mousePressed() {...} }

Setup Animate Interact

Start with a high-level look.

Final Project Example

slide-4
SLIDE 4

Animate

On every animation:

  • Aliens move
  • Torpedos move

Interact

ß Key pressed:

  • move ship left

à Key pressed:

  • move ship right

Mouse pressed:

  • Add torpedo

Bouncing Balls Racing Cars

Final Project Example

Rocket Paddle

Find worked examples!!

Keyboard Karel Rocket Paddle

slide-5
SLIDE 5

1. Understand chars and Strings

  • 2. Write methods acting on Strings
  • 3. Learn something interesting

Learning Goals

slide-6
SLIDE 6

Text Applications

slide-7
SLIDE 7

How is text represented?

slide-8
SLIDE 8

public void run() { String text = "hello!"; println(text); }

The variable type String

Text is stored using the variable type String. A String is a sequence of characters.

slide-9
SLIDE 9

1 2 3 4 5

H e l l o !

text

char c = text.charAt(index);

  • All characters in a string have an in

index.

  • You can access a character in the string via its in

index.

  • The le

length of a string is one larger than the last valid index in the string.

The variable type String

int len = text.length(); // 6

slide-10
SLIDE 10

What String actually is

char[] charArray ➕

str.length(); str.charAt(i); str.split(str); str.contains(str);

String str = Why do both of these exist in the Java language?

  • char[] builds off Java’s fundamental data storage
  • String adds convenient methods to char[]

Data storage Useful methods

slide-11
SLIDE 11

String Methods

public void run() { String example = "Hi mom"; int length = example.length(); println(length); char firstLetter = example.charAt(0); println(firstLetter); for(int i = 0; i < example.length(); i++) { char ch = example.charAt(i); println(ch); } }

🤕

slide-12
SLIDE 12

String Methods

public void run() { String example = "Hi mom"; // example of length method int length = example.length(); println(length); // prints 6 // example of getCharAt char firstLetter = example.charAt(0); println(firstLetter); // prints 'H’ // loop that prints letters one-by-one for(int i = 0; i < example.length(); i++) { char ch = example.charAt(i); println(ch); } }

6

example

H i m

  • m

1 2 3 4 5

length

6

slide-13
SLIDE 13

String Methods

public void run() { String example = "Hi mom"; // example of length method int length = example.length(); println(length); // prints 6 // example of getCharAt char firstLetter = example.charAt(0); println(firstLetter); // prints 'H’ // loop that prints letters one-by-one for(int i = 0; i < example.length(); i++) { char ch = example.charAt(i); println(ch); } }

6 H

example

H i m

  • m

1 2 3 4 5

length first Letter

6 'H'

slide-14
SLIDE 14

String Methods

public void run() { String example = "Hi mom"; // example of length method int length = example.length(); println(length); // prints 6 // example of getCharAt char firstLetter = example.charAt(0); println(firstLetter); // prints 'H’ // loop that prints letters one-by-one for(int i = 0; i < example.length(); i++) { char ch = example.charAt(i); println(ch); } } example

H i m

  • m

1 2 3 4 5

length first Letter i

6

6

H

'H'

ch

'H'

H

slide-15
SLIDE 15

String Methods

public void run() { String example = "Hi mom"; // example of length method int length = example.length(); println(length); // prints 6 // example of getCharAt char firstLetter = example.charAt(0); println(firstLetter); // prints 'H’ // loop that prints letters one-by-one for(int i = 0; i < example.length(); i++) { char ch = example.charAt(i); println(ch); } } example

H i m

  • m

1 2 3 4 5

length first Letter i

6

6

H

'H'

ch

'i'

H

1

i

slide-16
SLIDE 16

String Methods

public void run() { String example = "Hi mom"; // example of length method int length = example.length(); println(length); // prints 6 // example of getCharAt char firstLetter = example.charAt(0); println(firstLetter); // prints 'H’ // loop that prints letters one-by-one for(int i = 0; i < example.length(); i++) { char ch = example.charAt(i); println(ch); } } example

H i m

  • m

1 2 3 4 5

length first Letter i

6

6

H

'H'

ch

' '

H

2

i

slide-17
SLIDE 17

String Methods

public void run() { String example = "Hi mom"; // example of length method int length = example.length(); println(length); // prints 6 // example of getCharAt char firstLetter = example.charAt(0); println(firstLetter); // prints 'H’ // loop that prints letters one-by-one for(int i = 0; i < example.length(); i++) { char ch = example.charAt(i); println(ch); } } example

H i m

  • m

1 2 3 4 5

length first Letter i

6

6

H

'H'

ch

'm'

H

3

i m

slide-18
SLIDE 18

String Methods

public void run() { String example = "Hi mom"; // example of length method int length = example.length(); println(length); // prints 6 // example of getCharAt char firstLetter = example.charAt(0); println(firstLetter); // prints 'H’ // loop that prints letters one-by-one for(int i = 0; i < example.length(); i++) { char ch = example.charAt(i); println(ch); } } example

H i m

  • m

1 2 3 4 5

length first Letter i

6

6

H

'H'

ch

'o'

H

4

i m

slide-19
SLIDE 19

String Methods

public void run() { String example = "Hi mom"; // example of length method int length = example.length(); println(length); // prints 6 // example of getCharAt char firstLetter = example.charAt(0); println(firstLetter); // prints 'H’ // loop that prints letters one-by-one for(int i = 0; i < example.length(); i++) { char ch = example.charAt(i); println(ch); } } example

H i m

  • m

1 2 3 4 5

length first Letter i

6

6

H

'H'

ch

'm'

H

5

i m

  • m
slide-20
SLIDE 20

String Methods

public void run() { String example = "Hi mom"; // example of length method int length = example.length(); println(length); // prints 6 // example of getCharAt char firstLetter = example.charAt(0); println(firstLetter); // prints 'H’ // loop that prints letters one-by-one for(int i = 0; i < example.length(); i++) { char ch = example.charAt(i); println(ch); } } example

H i m

  • m

1 2 3 4 5

length first Letter i

6

6

H

'H'

H

6

i m

  • m
slide-21
SLIDE 21

How are characters represented?

slide-22
SLIDE 22

The primitive type char represents a single character or glyph. Some examples: char letterA = 'A'; char plus = '+'; char zero = '0'; char space = ' '; char newLine = '\n'; // special char first = text.charAt(0);

The variable type char

slide-23
SLIDE 23

The letter A, for example, has the ASCII value 65

Using portions of slides by Eric Roberts

ASCII

* This is only the first half of the table

slide-24
SLIDE 24

'A' à 'Z' are sequential. 'a' à 'Z' are sequential. '0' à ‘9' are sequential.

slide-25
SLIDE 25

public void run() { String str = readLine("Line: "); char ch = str.charAt(0); println("Original first char: " + ch); ch = Character.toUpperCase(ch); println("Uppercase first char: " + ch); if (Character.isLetter(ch)) { println("It’s a letter!"); } }

Useful Character methods

slide-26
SLIDE 26

Stay alert!

char ch = 'a'; Character.toUpperCase(ch); println(ch); char ch = 'a’; ch = Character.toUpperCase(ch); println(ch);

a

c

a A

c

A A A a

slide-27
SLIDE 27

static boolean isDigit(char ch)

Determines if the specified character is a digit.

static boolean isLetter(char ch)

Determines if the specified character is a letter.

static boolean isLetterOrDigit(char ch)

Determines if the specified character is a letter or a digit.

static boolean isLowerCase(char ch)

Determines if the specified character is a lowercase letter.

static boolean isUpperCase(char ch)

Determines if the specified character is an uppercase letter.

static boolean isWhitespace(char ch)

Determines if the specified character is whitespace (spaces and tabs).

static char toLowerCase(char ch)

Converts ch to its lowercase equivalent, if any. If not, ch is returned unchanged.

static char toUpperCase(char ch)

Converts ch to its uppercase equivalent, if any. If not, ch is returned unchanged.

Using portions of slides by Eric Roberts

Useful Character methods

slide-28
SLIDE 28

Strings have some unique properties

slide-29
SLIDE 29

l Java strings are im

immut utable able: once a string has been created yo you cannot set characters.

l To change a string: l Cr

Creat ate a ne a new s w str tring ing holding the new value you want it to have via concatenation (+).

l Reassigning the String variable (that’s allowed). l Impo

Import rtan ant c t conse nseque quenc nce: if you pass a String into a method, that method cannot modify that string.

Strings are Immutable

slide-30
SLIDE 30

public void run() { String s1 = "Breakout"; String s2 = "it was awesome"; String s3 = "I crushed " + s1 + " and " + s2; println(s3); }

Strings are often made through concatenation

I crushed Breakout and it was awesome

s1 "Breakout" s2 "it was awesome" s3 "I crushed Breakout and it was awesome"

slide-31
SLIDE 31

Many string algorithms use the “loop and construct” pattern.

Reversing a String

slide-32
SLIDE 32

H e l l

  • !

Reversing a String

slide-33
SLIDE 33

H e l l

  • !

H

Reversing a String

slide-34
SLIDE 34

H e l l

  • !

H e

Reversing a String

slide-35
SLIDE 35

H e l l

  • !

H e l

Reversing a String

slide-36
SLIDE 36

H e l l

  • !

H e l l

Reversing a String

slide-37
SLIDE 37

H e l l

  • !

H e l l

  • Reversing a String
slide-38
SLIDE 38

H e l l

  • !

H e l l

  • !

Reversing a String

slide-39
SLIDE 39

public void run() { println("This program reverses a string."); String str = readLine("Enter a string: "); String rev = reverseString(str); println(str + " spelled backwards is " + rev); }

ReverseString

str STRESSED

This program reverses a string. STRESSED Enter a string:

rev

skip simulation

Using portions of slides by Eric Roberts

reverseString

slide-40
SLIDE 40

public void run() { println("This program reverses a string."); String str = readLine("Enter a string: "); String rev = reverseString(str); println(str + " spelled backwards is " + rev); }

ReverseString

str STRESSED

This program reverses a string. STRESSED Enter a string:

rev DESSERTS private String reverseString(String str) { String result = ""; for ( int i = 0; i < str.length(); i++ ) { result = str.charAt(i) + result; } return result; } i str result STRESSED 1 2 3 4 5 6 7 8 S TS RTS ERTS SERTS SSERTS ESSERTS DESSERTS

skip simulation

Using portions of slides by Eric Roberts

reverseString

slide-41
SLIDE 41

public void run() { println("This program reverses a string."); String str = readLine("Enter a string: "); String rev = reverseString(str); println(str + " spelled backwards is " + rev); }

ReverseString

str STRESSED

This program reverses a string. STRESSED spelled backwards is DESSERTS STRESSED Enter a string:

rev DESSERTS

skip simulation

Using portions of slides by Eric Roberts

reverseString

slide-42
SLIDE 42

A pal palindr ndrome me is a string that reads the same forwards and backwards. For example:

l racecar l kayak l Mr. Owl ate my metal worm. l Go hang a salami! I'm a lasagna hog. l küçük l Ey Edip, Adana'da pide ye.

How would we use reverseString() to check if a word is a palindrome?

Palindrome

private String reverseString(String str) { String result = ""; for ( int i = 0; i < str.length(); i++ ) { result = str.charAt(i) + result; } return result; }

🤕

slide-43
SLIDE 43

Let’s Code it!

slide-44
SLIDE 44

private boolean isPalindrome(String original) { String reversed = reverseString(original); return reversed == original; }

Equality

Use str1.equals(str2) to compare strings, not str1 == str2

private boolean isPalindrome(String original) { String reversed = reverseString(original); return reversed.equals(original); }

slide-45
SLIDE 45

l Let's test our program on some examples: l racecar l kayak l go hang a salami! i'm a lasagna hog. l Ey Edip, Adana'da pide ye. l Will it work?

Some test cases

private boolean isPalindrome(String original) { String reversed = reverseString(original); return reversed.equals(original); }

slide-46
SLIDE 46

Here are some palindromes in other languages:

l 여보

여보, , 안경 안경 안보여 안보여 (Honey, I can't see my glasses)

l 上海自來水來自海上 (Shanghai tap water originates from "above" the

  • cean)

l कड़क (a loud thunderous sound) l

!ﻠﺢ ﺗﻌﻠﻖ ﺗﺤﺖ ﻗﻠﻌﺔ ﺣﻠﺐ(Dates hang underneath a castle in Halab)

The comedian Dmitri Martin also has a routine about palindromes; check it out at https://www.youtube.com/watch?v=0hUHDIOazIU

More Palindromes

slide-47
SLIDE 47

Useful String methods

slide-48
SLIDE 48

int length()

Returns the length of the string

char charAt(int index)

Returns the character at the specified index. Note: Strings indexed starting at 0.

String substring(int p1, int p2)

Returns the substring beginning at p1 and extending up to but not including p2

String substring(int p1)

Returns substring beginning at p1 and extending through end of string.

boolean equals(String s2)

Returns true if string s2 is equal to the receiver string. This is case sensitive.

int compareTo(String s2)

Returns integer whose sign indicates how strings compare in lexicographic order

int indexOf(char ch) or int indexOf(String s)

Returns index of first occurrence of the character or the string, or -1 if not found

String toLowerCase()

  • r

String toUpperCase()

Returns a lowercase or uppercase version of the receiver string

Using portions of slides by Eric Roberts

Useful String methods

slide-49
SLIDE 49

Useful String Methods

String original = "How now brown cow"; // replace all occurrences of " " with "!" String replaced = original.replaceAll(" ", "!"); println(replaced); // returns true if original contains the string "cow" println(original.contains("cow")); // String à String[], split on spaces " " String[] strArray = original.split(" "); for(int i = 0; i < strArray.length; i++) { println(strArray[i]); } // String[] à String, joined by ”@" String concatenated = String.join("@", strArray); println(concatenated); // How@now@brown@cow "How!now!brown!cow" true {"How","now", "brown","cow"} "How@now@brown@cow"

slide-50
SLIDE 50

The Caesar Cipher

Julius Caesar Jül Sezar

slide-51
SLIDE 51

The Caesar Cipher

ABCDEFGHIJKLMNOPQRSTUVWXYZ

English alphabet (26 letters) Encrypt: shift by key = 3 Decrypt: shift by key = -3

🤕

slide-52
SLIDE 52

How the cipher works

ASCII uppercase:

Cipher key=3

Shifted by key=3

char ch = 'A'; char chShift = ch + 3; println("plain : " + ch); println("cipher: " + chShift); Type mismatch: cannot convert from int to char

65 66 67 68 69 70 … 87 88 89 90 A B C D E F … W X Y Z 68 69 70 71 72 73 … 90 65 66 67 D E F G H I … Z A B C 68 69 70 71 72 73 … 90 65 66 67 D E F G H I … Z A B C

Java autoconverts char to int!!

slide-53
SLIDE 53

char ch = 'A'; int chIntShift = ch + key; char chShift = (char) chIntShift; println("plain: " + ch); println("ASCII: " + (int) ch); println("cipher: " + chShift);

How the cipher works

65 66 67 68 69 70 … 87 88 89 90 A B C D E F … W X Y Z

ASCII uppercase:

Cipher key=3

68 69 70 71 72 73 … 90 65 66 67 D E F G H I … Z A B C

Shifted by key=3

plain: A ASCII: 65 cipher: D

Java autoconverts char to int!!

slide-54
SLIDE 54

How the cipher works

65 66 67 68 69 70 … 87 88 89 90 A B C D E F … W X Y Z

ASCII uppercase:

Cipher key=3

68 69 70 71 72 73 … 90 65 66 67 D E F G H I … Z A B C

Shifted by key=3

plain: Y cipher: \

🤕

ASCII 92

char ch = 'Y'; int chIntShift = ch + key; char chShift = (char) chIntShift; println("plain: " + ch); println("cipher: " + chShift);

slide-55
SLIDE 55

char ch = 'Y’; int chIntShift = ch + key; if(chIntShift > 90) { chIntShift -= 26; } char chShift = (char) chIntShift; println("plain : " + ch); println("cipher: " + chShift);

How the cipher works

65 66 67 68 69 70 … 87 88 89 90 A B C D E F … W X Y Z

ASCII uppercase:

Cipher key=3

68 69 70 71 72 73 … 90 65 66 67 D E F G H I … Z A B C

Shifted by key=3

plain: Y cipher: B ASCII 66: 92-26

slide-56
SLIDE 56

How the cipher works

%

I’m Modulo! Remember me?

int chIntShift = 'A' + (ch - 'A' + key) % 26; char chShift = (char) chIntShift;

'Y' - 'A’ = 89 – 65= 24 'Y' - 'A' + key = 24 + 3 = 27 ('Y' - 'A' + key) % 26 = 1 'A' + ('Y' - 'A' + key) % 26 = 66

65 66 67 68 69 70 71 … 88 89 90 A B C D E F G … X Y Z ASCII uppercase:

slide-57
SLIDE 57

Allowing all ASCII symbols

65 66 67 68 69 70 71 … 88 89 90 A B C D E F G … X Y Z

ASCII uppercase:

97 98 99 100 101 102 103 … 120 121 122 a b c d e f g … x y z

ASCII lowercase:

if (Character.isUpperCase(ch)) { // shift by key // ensure resulting ASCII is between 65 and 90 } else if (Character.isLowerCase(ch)) { // shift by key // ensure resulting ASCII is between 97 and 122 } else { // do nothing }

slide-58
SLIDE 58

1. Understand chars and Strings

  • 2. Write methods acting on Strings
  • 3. Learn something interesting

Learning Goals

slide-59
SLIDE 59

Your goals today

Console/Graphics, Games/Stories, Puzzles/Adventures, Math/Medicine/Science, …The ArrayList goes on! Du Due by by 6p 6pm to tomorrow (1) Array exercise: MinMaxMean (+ ArrayList exercises) Su Submit b by en end of Lab ab 2, ev even if you are not do done ne (2) Final Project (start by Lab 3)