Java Strings - PowerPoint PPT Presentation

1 / 48
About This Presentation
Title:

Java Strings

Description:

Adding a number to a string. int nNum = 5; g.drawString('Total: ' nNum, 20, 20) ... tag name, e.g. 'b', and a word such as 'Yay', create a String with HTML tags ... – PowerPoint PPT presentation

Number of Views:521
Avg rating:3.0/5.0
Slides: 49
Provided by: paulc1
Category:
Tags: hello | java | string | strings

less

Transcript and Presenter's Notes

Title: Java Strings


1
Java Strings
  • String sString "hello"
  • is the almost the same as
  • String sString new String("hello")
  • so most of the time you can get away with it.
  • Good Style use new

2
Adding a number to a string
  • int nNum 5
  • g.drawString("Total " nNum, 20, 20)
  • //displays Total 5
  • The operator can be used to add a number to a
    stringmuch easier than C!
  • The order makes a difference!
  • g.drawString("X" 2 3, 20, 20)
  • //displays X23
  • g.drawString("X" (2 3), 20, 20)
  • //displays X5

3
More String stuff
  • String methods you should know
  • equals()
  • equalsIgnoreCase()
  • toUpperCase()
  • toLowerCase()
  • compareTo()
  • indexOf()
  • length()
  • charAt()

4
More String stuff
  • String sString1 "hello"
  • String sString2 "HeLlO"
  • if(sString1.equals(sString2))
  • System.out.println("equals")
  • if(sString1.equalsIgnoreCase(sString2))
  • System.out.println("equalsIC")
  • System.out.println(sString1.toUpperCase())
  • / sample output
  • equalsIC
  • HELLO/

5
More String stuff
  • String sString1 "apple"
  • String sString2 "banana"
  • String sString3 "banana"
  • System.out.println(sString1.compareTo(sString2))
  • System.out.println(sString3.compareTo(sString2))
  • System.out.println(sString2.indexOf('n'))
  • System.out.println(sString2.indexOf('n',3))
  • System.out.println(sString2.indexOf('x'))
  • / Sample Output
  • -1
  • 0
  • 2
  • 4
  • -1 //not found, no 'x' in banana!
  • /

6
What is the output of this program fragment?
  • System.out.println(mystery("Defended"))
  • System.out.println(mystery("Detonated"))
  • System.out.println(mystery("Civic")) //Watch
    out!
  • //other code not shown
  • public int mystery(String sString)
  • String sMyst sString.toUpperCase()
  • int nNum sString.length() - 1
  • int nI 0
  • while(sMyst.charAt(nI) sMyst.charAt(nNum))
  • System.out.println(sString.charAt(nI)
  • "?" sString.charAt(nNum
    ))
  • nI
  • nNum--

7
input TextArea and Button
  • There is no "easy way" (like cin in C) to get
    input from a user in Java
  • There are several components that can get user
    input
  • For assignment 14 we'll use two TextArea and
    Button
  • Java is consistent, if you know how to work with
    Button, TextArea is pretty much the same

8
input TextArea and Button
  • public class TextAreaDemo extends Applet
  • implements ActionListener
  • TextArea bob
  • Button bill
  • String sInput new String()
  • public void init()
  • bob new TextArea()
  • add(bob)
  • bill new Button()
  • add(bill)
  • bill.addActionListener(this)
  • public void paint(Graphics g)
  • g.drawString("Input is " sInput, 50, 260 )
  • public void actionPerformed(ActionEvent ae)
  • sInput bob.getText()
  • repaint()

9
input TextArea and Button
10
StringTokenizer
  • Sometimes you have multiple words in one String,
    and you want to parse the String for the
    individual words
  • One way to do this is with StringTokenizer
  • To use it, you will need to
  • import java.util.

11
StringTokenizer
  • StringTokenizer st
  • new StringTokenizer("this is a test")
  • while (st.hasMoreTokens())
  • System.out.println(st.nextToken())
  • prints the following output
  • this
  • is
  • a
  • test
  • For more information read
  • Java API page on StringTokenizer

12
Find the output of this fragment
  • String sInput "The quick brown fox jumped over
  • the lazy red dog"
  • System.out.println(mystery(sInput))
  • mystery2(sInput)
  • //other java code not shown
  • public int mystery(String sString)
  • for(int nI 0 nI
  • if(sString.charAt(nI) 'w')
  • return nI
  • return -1
  • public void mystery2(String sString)
  • StringTokenizer st
  • new StringTokenizer(sString)
  • while (st.hasMoreTokens())

13
substring() one argument
  • returns the rest of the String beginning at that
    index
  • Examples
  • "unhappy".substring(2) returns "happy"
  • "Harbison".substring(3) returns "bison"
  • "emptiness".substring(9) returns "" (empty
    String)

14
substring() two arguments
  • returns part of the String beginning at that
    first index, and ending one position before the
    second index
  • Examples
  • "hamburger".substring(4, 8) returns "urge"
  • "smiles".substring(1, 5) returns "mile"

15
JavaBat practice problemString1 middleTwo
  • http//www.javabat.com/prob?idString1.middleTwo
  • Given a string of even length, return a string
    made of the middle two chars, so the string
    "string" yields "ri". The string length will be
    at least 2.
  • middleTwo("string") ? "ri"
  • middleTwo("code") ? "od"
  • middleTwo("Practice") ? "ct"

16
JavaBat practice problemString1 makeTags
  • http//www.javabat.com/prob?idString1.makeTags
  • Given an HTML tag name, e.g. "b", and a word such
    as "Yay", create a String with HTML tags
    surrounding the word, such as "Yay".
  • makeTags("b", "Yay") ? "Yay"
  • makeTags("cite", "Yay") ? "Yay"
  • makeTags("i", "Hello") ? "Hello"

17
Problem write a function that reverses a string
  • public String reverse(String str)
  • ???

18
Problem write a function that reverses a string
  • public String reverse(String str)
  • String sNew new String()
  • ???
  • return sNew

19
Problem write a function that reverses a string
  • public String reverse(String str)
  • String sNew new String()
  • int nLast str.length()-1
  • for(int nInLast nI0 nI--)
  • ???
  • return sNew

20
Problem write a function that reverses a string
  • public String reverse(String str)
  • String sNew new String()
  • int nLast str.length()-1
  • for(int nInLast nI0 nI--)
  • sNew sNew str.charAt(nI)
  • return sNew

21
JavaBat practice problemString2 doubleChar
  • http//www.javabat.com/prob?idString2.doubleChar
  • Given a string, return a string where for every
    char in the original, there are two chars.
  • doubleChar("The") ? "TThhee"
  • doubleChar("AAbb") ? "AAAAbbbb"
  • doubleChar("Hi-There") ? "HHii--TThheerree"

22
How a slot machine works
23
How a slot machine works
Pulling the handle causes the three reels to
begin spinning. The reels spin independently.
Lets say each reel has 7 symbols. The total
number of possible combinations would be 7 x 7 x
7 343
24
Modeling a slot machine
  • In Assignment 15, we will have three reels each
    with 32 symbols

25
Modeling a slot machine
  • In Assignment 15, we will model each reel with an
    Array List
  • public class SlotMachine
  • ArrayList reel1
  • //other class members not shown
  • public void init()
  • reel1 new ArrayList()
  • reel1.add(new String(Blank))
  • reel1.add(new String(Bars))
  • //and so on. . .

26
Modeling a slot machine
  • Then every time we click the Play button, we
    choose a random symbol and display it in one of
    the TextFields
  • public void actionPerformed(ActionEvent ae)
  • //pick one of the symbols on the reel
  • String sWin1 reel1.get(??)
  • //display it in the TextField win1
  • win1.setText(sWin1)

27
preconditions and postconditions
  • preconditions tell you what you DON'T have to
    deal with
  • postconditions are what you DO have to deal with
  • double divideBySelf(double dX)
  • //precondition dX is non-zero
  • //postcondition returns dX/dX

28
preconditions and postconditions
  • double divideBySelf(double dX)
  • //precondition dX is non-zero
  • //postcondition returns dX/dX
  • return dX/dX

29
preconditions and postconditions
  • double divideBySelf(double dX)
  • //precondition dX is a real number
  • //postcondition returns 0 if dX is zero,
    otherwise returns dX/dX

30
preconditions and postconditions
  • double divideBySelf(double dX)
  • //precondition dX is a real number
  • //postcondition returns 0 if dX is
  • // zero, otherwise returns dX/dX
  • if(dX 0)
  • return 0
  • else
  • return dX/dX

31
Practice Quiz Question
  • Write the method
  • int numLetters(String sString)
  • / precondition sString has a length 0
  • postcondition returns the number of characters
  • that are letters of the alphabet
  • in the String argument
  • /
  • Examples
  • numLetters("apple!") returns 5
  • numLetters("_at_!") returns 0
  • Hint use public static boolean isLetter(char ch)
  • from the Character class. For example
    Character.isLetter('a') is true and
    Character.isLetter('2') is false

32
Practice Quiz Question
  • import java.awt.
  • import java.applet.
  • public class CountChars extends Applet
  • public void init()
  • System.out.println(numLetters("apple!"))
  • System.out.println(numLetters("_at_!"))
  • System.out.println(numLetters(""))
  • System.out.println(numLetters("a_2(3xF"))
  • /Sample Output
  • 5
  • 0
  • 0
  • 3 /
  • int numLetters(String sString)
  • / precondition sString has a length 0
  • postcondition returns the number of
    characters

33
JavaBat practice problemString2 mixString
  • http//www.javabat.com/prob?idString2.mixString
  • Given two strings, A and B, create a bigger
    string made of the first char of A, the first
    char of B, the second char of A, the second char
    of B, and so on. Any leftover chars go at the end
    of the result.
  • mixString("abc", "xyz") ? "axbycz"
  • mixString("Hi", "There") ? "HTihere"
  • mixString("xxxx", "There") ? "xTxhxexre"

34
Practice Quiz Question Two Ending Punctuation
methods
  • import java.awt.
  • import java.applet.
  • public class Punctuation extends Applet
  • public void init()
  • System.out.println(countEndPunc("What, is-
    that?"))
  • System.out.println(countEndPunc("Stop!Look!Liste
    n!"))
  • System.out.println(countEndPunc("Eat your
    spinach. Now!"))
  • System.out.println(countEndPunc(""))
  • System.out.println(countEndPunc("hmmm . . .
    ."))
  • / Sample Output
  • 1
  • 3
  • 2
  • 0
  • 4 /
  • boolean isEndPunc(char cPunc)
  • //postcondition returns true if cPunc is one of
    the

35
A Card Game
  • Three cards are dealt to each player
  • The score for the hand is calculated

36
The "Map"
10
RRR
RRB RBR BRR
3
RBB BBR BRB
1
BBB
0
37
The "Map"
"Key"
"Value"
10
RRR
RRB RBR BRR
3
RBB BBR BRB
1
BBB
0
38
The Map interface (AB only)
  • Implemented by HashMap and TreeMap
  • For every "Key" there can be only one "Value"
  • No iterator! (e.g. you won't be expected to
    display all items)
  • public interface Map
  • Object put(Object key, Object value)
  • Object get(Object key)
  • Object remove(Object key)
  • boolean containsKey(Object key)
  • int size()
  • Set keySet()

39
Creating a Map
  • import java.util.
  • Map theMap
  • new HashMap ()
  • //or new TreeMap ()
  • theMap.put("RRR", new Integer(10))
  • theMap.put("RRB", new Integer(3))
  • theMap.put("RBR", new Integer(3))
  • theMap.put("BRR", new Integer(3))
  • theMap.put("RBB", new Integer(1))
  • theMap.put("BRB", new Integer(1))
  • theMap.put("BBR", new Integer(1))
  • theMap.put("BBB", new Integer(0))
  • String sHand1 "BRR"
  • Integer score (Integer)theMap.get(sHand1)
  • System.out.println(score.intValue())
  • //Displays 3

40
get() returns null if the Key is not in the map
  • String sHand1 "XXX"
  • Integer score (Integer)theMap.get(sHand1)
  • System.out.println(score.intValue())
  • /
  • Exception in thread "main" java.lang.NullPointerEx
    ception at CardMap.main(CardMap.java22)
  • Press any key to continue... /

41
containsKey() checks to see if the Key is not in
the map
  • String sHand1 "XXX"
  • Integer score
  • if(theMap.containsKey(sHand1))
  • score (Integer)theMap.get(sHand1)
  • else
  • score new Integer(-1)
  • System.out.println(score.intValue())
  • //Displays -1

42
What is the output?
  • String sHand1 new String()
  • String sHand2 new String()
  • for(int nI 0 nI
  • if(nI2 0)
  • sHand1 deal(nI)
  • else
  • sHand2 deal(nI)
  • System.out.println(theMap.get(sHand1))
  • System.out.println(theMap.get(sHand2))
  • String deal(int nNum)
  • if(nNum30 nNum 5 0)
  • return "R"
  • else
  • return "B"

43
SuperLotto Plus
  • Pick a set of five numbers (no duplicates) from
    1 to 47 and a MEGA number from 1 to 27
  • While the set of five numbers has no duplicates,
    the mega number may be a duplicate

44
SuperLotto Plus
  • Winning Ticket Value is determined by the number
    of matching numbers
  • Ticket Value varies with each drawing

45
The Set interface (AB only)
  • A Set is a collection of objects with no
    duplicates
  • Java has a Set interface to model Sets
  • Java has two classes that implement Set
  • TreeSet
  • HashSet
  • Just like List and Map, the code is identical

46
The Set interface (AB only)
  • interface Set
  • boolean add(Object o)
  • //Adds an element if it is not already
  • //stored in this set.
  • boolean contains(Object o)
  • //Returns true o is in set, false otherwise
  • Iterator iterator()
  • //Returns an Iterator that provides access
  • //to the the elements of this set.
  • boolean remove(Object o)
  • //Removes o from set and returns true if o
  • //is in set if not present returns false.
  • int size()
  • //Returns the number of elements in this set.

47
Problem Create a set of three random integers
with no duplicates
  • Set threeNums new TreeSet()
    //or new HashSet()
  • while(threeNums.size()
  • Integer temp new Integer(int(Math.random()1
    0)
  • threeNums.add(temp)
  • Iterator i threeNums.iterator()
  • while(i.hasNext())
  • System.out.println(i.next())
  • /Sample Output
  • 2
  • 3
  • 7
  • Press any key to continue/

48
What is the output?
  • Set theSet new TreeSet()
  • theSet.add(new Integer(9))
  • theSet.add(new Integer(3))
  • theSet.add(new Integer(9))
  • theSet.add(new Integer(-3))
  • System.out.println("Size is " theSet.size())
  • if(theSet.contains(new Integer(-3)))
  • System.out.println("-3 is in the set")
  • else
  • System.out.println("-3 is NOT in the set")
  • if(theSet.remove(new Integer(2)))
  • System.out.println("2 removed")
  • else
  • System.out.println("2 was not removed")
Write a Comment
User Comments (0)
About PowerShow.com