Skip to content
This repository was archived by the owner on Sep 22, 2024. It is now read-only.

Commit 53951b5

Browse files
committed
Finish Sentence.java
1 parent 2b2b5f4 commit 53951b5

File tree

1 file changed

+25
-12
lines changed

1 file changed

+25
-12
lines changed

Sentence.java

Lines changed: 25 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -5,36 +5,49 @@ public class Sentence {
55

66
public ArrayList<Integer> getBlankPositions() {
77
ArrayList<Integer> blankPositions = new ArrayList<Integer>();
8-
int i;
9-
for (i = 0; i < sentence.length() - 1; i++) {
10-
if (sentence.substring(i, i + 1) == " ")
8+
for (int i = 0; i < sentence.length(); i++) {
9+
if (sentence.substring(i, i + 1).equals(" "))
1110
blankPositions.add(i);
1211
}
1312
return blankPositions;
1413
}
1514

1615
public int countWords() {
17-
return 5;
16+
return getBlankPositions().size() + 1;
1817
}
1918

2019
public String[] getWords() {
21-
String[] words = new String[0];
2220
int wordCount = countWords();
21+
String[] words = new String[wordCount];
2322
ArrayList<Integer> blankPositions = getBlankPositions();
2423
int i;
25-
for (i = 0; i < wordCount; i++) {
26-
int start = 0;
27-
if (i > 0) start = blankPositions.get(i-1);
28-
String word = sentence.substring(start, blankPositions.get(i));
29-
words[i] = word;
30-
}
3124
if (blankPositions.size() == 0 && wordCount == 1) {
3225
words[0] = sentence;
26+
} else {
27+
for (i = 0; i < wordCount; i++) {
28+
int start = 0;
29+
if (i > 0)
30+
start = blankPositions.get(i - 1) + 1;
31+
if (blankPositions.size() == i) {
32+
String word = sentence.substring(start);
33+
words[i] = word;
34+
} else {
35+
String word = sentence.substring(start, blankPositions.get(i));
36+
words[i] = word;
37+
}
38+
}
3339
}
3440
return words;
3541
}
3642

3743
public static void main(String[] args) {
38-
44+
Sentence sentence1 = new Sentence();
45+
sentence1.sentence = "The bird flew away!";
46+
System.out.println(sentence1.getBlankPositions());
47+
System.out.println(sentence1.countWords());
48+
int i;
49+
for (i = 0; i < sentence1.countWords(); i++) {
50+
System.out.println(sentence1.getWords()[i]);
51+
}
3952
}
4053
}

0 commit comments

Comments
 (0)