Deniz Cetinalp
Deniz Cetinalp

Reputation: 911

Reverse each sentence

Say my input is

now is the time for
all good men to come to the aid of the party

The output would be:

for time the is now
party the of aid the to come to men good all

I figured out how to reverse each the whole text file but I need to do it sentence by sentence. Currently my code is outputting this:

party the of aid the to come to men good all for time the is now

Code is:

List<String> words = new ArrayList<String>();

while(sc.hasNextLine())
{
String line = sc.nextLine();
StringTokenizer st = new StringTokenizer(line);
while(st.hasMoreTokens())
{
words.add(st.nextToken());
}
}
for (int i = 0; i <words.size(); i++)
{
System.out.print(words.get(words.size()-i-1) + " ");
}

Upvotes: 0

Views: 648

Answers (3)

&#211;scar L&#243;pez
&#211;scar L&#243;pez

Reputation: 236114

It's simpler if you use the split() method of the String class for splitting a line, it's the preferred way to split by spaces (instead of using StringTokenizer, which is considered deprecated for all practical purposes). Also, you'll have problems with the line break after each line ends - in fact, you should use a list of lists, where each list holds the words of a single line. Try this instead:

List<List<String>> words = new ArrayList<List<String>>();

while (sc.hasNextLine()) {
    String line = sc.nextLine();
    words.add(Arrays.asList(line.split("\\s+")));
}

for (List<String> list : words) {
    for (int i = list.size()-1; i >= 0; i--)
        System.out.print(list.get(i) + " ");
    System.out.println();
}

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726809

Move the declaration of words inside the loop - put it right after the declaration of StringTokenizer. This would ensure that the word list is re-initialized each time that you go through a new sentence.

Upvotes: 1

PearsonArtPhoto
PearsonArtPhoto

Reputation: 39698

All you need to do is move the print statement into the while loop, and clear the words ArrayList. This will print each sentence out before moving on to the next line, and make sure the list is clear to start storing the next sentence.

while(sc.hasNextLine())
{
  String line = sc.nextLine();
  StringTokenizer st = new StringTokenizer(line);
  while(st.hasMoreTokens())
  {
    words.add(st.nextToken());
  }
  for (int i = 0; i <words.size(); i++)
  {
    System.out.print(words.get(words.size()-i-1) + " ");
  }
  words.clear();
}

Upvotes: 1

Related Questions