0

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) + " ");
}
PearsonArtPhoto
  • 38,970
  • 17
  • 111
  • 142
Deniz Cetinalp
  • 901
  • 1
  • 18
  • 34

3 Answers3

2

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();
}
Community
  • 1
  • 1
Óscar López
  • 232,561
  • 37
  • 312
  • 386
  • Also, for the output, just iterate backwards `for (int i = words.size -1; i > 0; i--)` which should be far more efficient than using Collections.reverse() first - if you only want to output the words in reverse order. Otherwise, Collections.reverse() is the way you go. – user3001 Nov 23 '12 at 01:00
  • @user3001 there's a little problem in your code - the condition should be `i>=0`, but it's a good idea nevertheless. I updated my answer with your suggestion. – Óscar López Nov 23 '12 at 01:10
1

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();
}
PearsonArtPhoto
  • 38,970
  • 17
  • 111
  • 142
1

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523