I'm working on Problem A on this page, and I have the program working correctly sort of. However, when I go to my output file, I see two blank lines one at the beginning of the file, and one at the end of the file.
Yet I have no idea, why these lines are appearing at the end of the file.
Basically you have to split a sentence into words, and check the length of each word. I've tried two methods of doing this, one with the split method of the String class, and one with the StringTokenizer class, and I'm still having this problem. Any ideas as to where the blank lines are coming from?
The code using the StringTokenizer:
Code:package contest_problems; import java.io.*; import java.util.*; /** * * @author James */ public class PA98 { public static void main(String[] args) throws IOException { Scanner fin = new Scanner(new FileReader("censor.in")); PrintWriter fout = new PrintWriter(new FileWriter("censor.out")); String sSentence = ""; StringTokenizer st; String sWord = ""; fin.nextInt(); while (fin.hasNextLine()) { sSentence = fin.nextLine(); st = new StringTokenizer(sSentence); while (st.hasMoreTokens()) { sWord = st.nextToken(); if (sWord.length() == 4) { fout.print("**** "); } else { fout.print(sWord + " "); } } fout.println(); } fout.close(); } }
Just a thought: you aren't making sure you have printed anything before calling fout.println();
Yeah I can tell that the Strings are being printed to the properly just the output file looks weird.
My output file is attached. I had to rename it to censor.txt to get it to upload though. Any chance that the StringTokenizer adds a new line that I don't know about?
Edit: If I change the println() where I'm printing the sentences to print() it prints it out on one line.
As far, as I can tell, those two new lines shouldn't be there.
Last edited by chili5; 05-09-2009 at 04:33 AM.
I can't see why there would be a blank line at the beginning of the file, but if you wish to use print instead of println then instead of the last 'fout.println()' call just add a '\n' to the end of the last word on each line.
Code:while (fin.hasNextLine()) { sSentence = fin.nextLine(); st = new StringTokenizer(sSentence); while (st.hasMoreTokens()) { sWord = st.nextToken(); if (sWord.length() == 4) { fout.print("**** "); } else { fout.print(sWord + " "); } } fout.print('\n'); }
Well this is just weird, that didn't work. Any honestly I don't think there should even be a new line at all. :\
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks