|
home—info—lects—labs—exams—hws
textbook—tutor/PIs—java.lang docs—java.util docs
Write a method which takes in an array-of-strings, and returns an acronym: the first letter of each word, capitalized, each followed by a period. For example:
String[] equipment = new String[5]; equipment[0] = "self"; equipment[1] = "contained"; equipment[2] = "underwater"; equipment[3] = "breathing"; equipment[4] = "apparatus"; System.out.println( "Expect: \"S.C.U.B.A.\", got \"" + acronym(equipment) + "\"." ); |
Hint:
the type of your “so-far” variable
should be the same as your method's return type.
(Recall the countdown method,
from when we first introduced loops.)
Modify your main to convert strings to acronyms interactively: read a line (using the Scanner method nextLine()), splitting the line into an array of words (using split, described below), and print the acronym.
Helpful method:
For a (long) String s which contains several words,
calling s.split(" ")
splits s into words
and returns each word into an array.
(The " " passed to the method is how split
decides where one ‘word’ ends and the next begins1.)
PotionBottle[] inventory = new PotionBottle[5]; inventory[0] = new PotionBottle( "blue", 1.0, 3 ); inventory[1] = new PotionBottle( "green", 0.5, 10 ); inventory[2] = new PotionBottle( "green", 0.5, 2 ); inventory[3] = new PotionBottle( "clear", 0, 7 ); inventory[4] = new PotionBottle( "yellow", 1.0, 0 ); |
Really, you should indicate that words are separated by “one or more spaces”, which is denoted by " +", a regular expression meaning “one or more occurrence of a space character”.
In fact, if you want, you can provide fancier regular expressions so split, so that it will split words by one or more punctuation or spaces: split("[ ,!?-']+"). The “[…]” means “any of the characters enclosed in the brackets”, and the “+” means “one or more of the previous thing”.
↩home—info—lects—labs—exams—hws
textbook—tutor/PIs—java.lang docs—java.util docs
©2009, Ian Barland, Radford University Last modified 2009.Apr.21 (Tue) |
Please mail any suggestions (incl. typos, broken links) to ibarlandradford.edu |