Question

The goal of my program is to ask user to enter a sentence and then reverse the words in that sentence while using a vector.

import java.io.*;
import java.util.*;

public class ReverseVector {

public static void main(String []args){

   Scanner scan = new Scanner(System.in);
   Vector<String> vec =new Vector<String>();
   String word = "";          

       System.out.print("Enter a sentence  :");

       for(int i=0;i<=vec.size();i++){          
               word=scan.next();                   
               vec.add(word); //adding each word to an element.              
       }

      Collections.reverse(vec);
      System.out.println(vec);                    
  }
}  

I am looking for suggestions on how to break from the for loop once all of the words have been added to the vector. My thought is some sort of if statement that states if there are no more words to add to vector then break.

The program should do the following:

Enter a sentence: The bird flew high

Output:

high flew bird The
Was it helpful?

Solution

One way to do this is to use scan.nextLine() to read the entire line; this essentially uses the "newline" to indicate the end of the sentence.

Now you'll have a String containing the whole sentence. Then you can split the string into words with e.g. String.split():

String sentence = scan.nextLine();
String[] words = sentence.split("\\s+"); // <= sequence of one or more whitespace

for (String word : words)
    vec.add(word);

You could also use a second Scanner to read the words from the sentence string, if you'd like to stay away from the regular expressions of String.split(), e.g.:

String sentence = scan.nextLine();
Scanner sentenceScan = new Scanner(sentence);

while (sentenceScan.hasNext())
    vec.add(sentenceScan.next());

The key there is hasNext(). You may be tempted to use scan.hasNext() on your original scanner but, unfortunately, this will not get the job done, as hasNext() will continue to return true until the end-of-file on the input is reached (and a newline input is not an end-of-file).

By the way, note that in your original code:

for(int i=0;i<=vec.size();i++)

Here, vec.size() is initially 0, so this loop would never execute anyways. One advantage of using dynamically sized containers (such as Vector) over arrays is that you can add elements to them as needed. So instead of looping to vec.size(), which couldn't be known ahead of time anyways (you don't know how many words will be entered), loop over all the input words and just add() them to the vector.


Attempting to break down the while loop in the second example as requested in comments. This while loop:

while (sentenceScan.hasNext())
    vec.add(sentenceScan.next());

Essentially this is a direct translation of the English sentence: "While there are more words, get the next word and add it to vec." It's always good when your code clearly reflects your intentions, but we can break it down a little to see how it works:

We know the following:

  • while (condition) loops while condition is true.
  • sentenceScan.hasNext() returns true if it can get another word from the sentence, and false if it can not (i.e. if the end of the sentence string is reached).
  • sentenceScan.next() will read the next word from the sentence string and return it. Internally, the scanner moves past this word when it reads it (it keeps track of its current position in the sentence string behind the scenes). So each time you call next(), it effectively grabs the next word from the string and "consumes" that word so the next time you call next(), it gets the following word. If you try and call next() when there are no more words, it will throw an exception (see linked documentation).
  • vec.add(...) of course appends whatever to the end of the Vector.

So let's expand this like so:

while (true) { // loop "forever", since we don't know when we'll stop
    if (!sentenceScan.hasNext()) // if there are no more words... 
        break; // ...get the heck out of this loop!
    String word = sentenceScan.next(); // get next word from scanner
    vec.add(word); // add that word to the vector
}

For brevity we can skip some steps, for example, we don't really need that word variable since we only use it in one place, so:

while (true) { // loop "forever", since we don't know when we'll stop
    if (!sentenceScan.hasNext()) // if there are no more words... 
        break; // ...get the heck out of this loop!
    // get next word from scanner and add it to vector, in one fell swoop:
    vec.add(sentenceScan.next());
}

And since our condition for breaking out of the loop is simple, at the beginning of the loop, and based on a boolean value, we can just make it be the actual loop condition:

while (sentenceScan.hasNext()) { // loop until there are no more words
    // get next word from scanner and add it to vector:
    vec.add(sentenceScan.next());
}

And so we have the loop from that second example. Hopefully that makes sense!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top