|
home—info—exams—lectures—labs—hws
Recipe—Laws—lies—syntax—java.lang docs—java.util docs
We'll the lecture solidifying our knowledge, working through the examples of lab01b—your turn: a function from scratch: buffetPrice, toppingArea (missed for snow day). We'll stress:
Read the following section about Strings; we'll practice with them in lab tomorrow:
We have seen two types of data so far, in Java: int, and double. Today we consider a third: Strings.
Strings -- that is, strings of characters in a row -- are Java's name for what most people call text. For example,
Strings are great for representing various data:
We saw a String with five characters between the quotation marks, and another with two character. Can you write down a String with only one character? Okay, good. How about even shorter than one character? Sure! Type a quotation-mark, then type zero characters, and then the closing quotation-mark:
"" |
With numbers, Java has built-in arithmetic functions like + and * (in addition to the special math-package functions Math.sqrt, Math.cos, etc.), so you can start doing fun stuff with numbers immediately. What can we actually do with strings?
It turns out there are many interesting built-in functions on strings, but one which is particularly handy is concatenating strings. In part, it's handy because Java provides a shortcut name for this: +. That is,
"hello" + "there" |
"Hello" + " " + "there" + "," + " sailor." |
tip: It's easy to forget the + between strings. Spot the missing plus in:Also, it's easy to get 0 or 2 spaces, instead of 1, when doing a lot of string concatenation.
"Hello " + "there" + ", " "Sailor" + " " + "Moon"
Just as 0 and 1 are numbers that are particular easy to compute with, the empty string, "", is particularly easy to concatentate. Always use "" as a test case, unless that's a clearly nonsensical test case.
Exercise: Complete the following function, using + for Strings:
/** Return the sound of an echo, of a given phrase. * @param _____ The phrase to shout at a cliff-side. * @return The sound returned * p.echo2( "hello" ) = "hello, hello." * p.echo2( "Who's there?" ) = "Who's there?, Who's there?." * p.echo2( "z" ) = ______ * p.echo2( "" ) = ______ */ _____ echo2( _____ _____ ) { return ____________________________; } |
Exercise:
/** Return something Beavis might say, in response to just * about any trigger word. * @param _____ The trigger word, for Beavis's response. * @return Beavis's catchphrase. * p.beavis( "but" ) = "Heh heh, you said 'but'." * p.beavis( "phenylalanine" ) = "Heh heh, you said 'phenylalanine'." * p.beavis( "" ) = "Heh heh, you said ''." */ _____ beavis( _____ _____ ) { return ____________________________; } |
home—info—exams—lectures—labs—hws
Recipe—Laws—lies—syntax—java.lang docs—java.util docs
©2008, Ian Barland, Radford University Last modified 2008.Jan.24 (Thu) |
Please mail any suggestions (incl. typos, broken links) to ibarlandradford.edu |