I need to do this exercise with java and I don't even know where to begin, someone told me I should use StringTokenizer and I have no idea how to use it or do anything else on the exercise. Can some of you help me? I'm watching tutorials on java but I don't get nothing ...
Asked
Active
Viewed 78 times
-5
-
If you want help, please read [ask] and [the on-topic section](http://stackoverflow.com/help/on-topic) so that you write a question that will get answered. – Jonathan Drapeau Jun 19 '14 at 17:25
-
Are we doing your homework for you? Yes, a StringTokenizer would work just fine here to break up your original sentence. Check out the [javadoc](http://docs.oracle.com/javase/7/docs/api/java/util/StringTokenizer.html), it gives you a good example. – ticktock Jun 19 '14 at 17:26
-
The string tokenizer class allows an application to break a string into tokens.Its very simple just use StringTokenizer class to split the input string and write it to a file using OutputStream. You can [refer for StringTokenizer](http://docs.oracle.com/javase/7/docs/api/java/util/StringTokenizer.html) [refer for OutputStream](http://docs.oracle.com/javase/tutorial/essential/io/file.html) – SparkOn Jun 19 '14 at 17:48
1 Answers
0
The first step is to take your string and change it into a list of words. This can be accomplished with the following code:
String initialString = "..."; //Whatever your string is
String[] words = initialString.split(" "); //Split by spaces to get word list
Next, you have to open a file that you can write the words to. You create an instance of PrintWriter
, whose constructor two parameters (the file name and the encoding, usually UTF-8
). You create the PrintWriter with the following code:
PrintWriter write = new PrintWriter("output.txt", "UTF-8");
Just remember that whatever file name you specify to PrintWriter will be completely overwritten!
Finally, you loop through the list of words and write each one to the file with a modified for-loop:
for (String word : words)
write.writeln(word);
and close the writer:
write.close();
Thus, the final code looks like this:
import java.io.PrintWriter;
public class WriteWords {
public static void main(String[] args)
{
//You can obviously change this :)
String sentence = "I am using Java to do text processing instead of Perl.";
String[] words = sentence.split(" ");
//Change "output.txt" to whatever your file is
PrintWriter write = new PrintWriter("output.txt", "UTF-8");
for (String word : words)
write.writeln(word);
write.close();
}
}

Raghav Malik
- 751
- 1
- 6
- 20