Page 722 - AP Computer Science A, 7th edition
P. 722

2. (a) public List<Integer> getBlankPositions() {
List<Integer> posList = new ArrayList<Integer> ();
for (int i = 0; i < sentence.length(); i++)
{
if (sentence.substring(i, i + 1).equals(" "))
posList.add(i);
}
return posList; }
Alternatively (an inferior, unnecessarily complicated solution!),
public List<Integer> getBlankPositions() {
List<Integer> posList = new ArrayList<Integer> ();
String s = sentence;
int diff = 0;
int index = s.indexOf(" "); while (index >= 0)
{
posList.add(index + diff);
diff = sentence.length() – (s.substring(index + 1)).length(); s = s.substring(index + 1);
index = s.indexOf(" ");
}
return posList; }
(b) public int countWords() {
return getBlankPositions().size() + 1; }
(c) public String[] getWords() {












































































   720   721   722   723   724