First, this is the first programming class I’ve taken, so I apologize if this is a pretty simple problem. for a homework assignment, we have to write a program which scans a text file, prompts the user for words identified by < >, and then writes the result to another text file.
The problem I’m having is that the output file is all written on a single line, instead of preserving the line breaks from the input file.
For example:
The input
looks like
this text.
the output looks like this text.
This is the code I have in the relevant method.
public static void createMadLib(Scanner console) throws FileNotFoundException {
Scanner input = getInput(console);
System.out.print("Output file name: ");
PrintStream out = new PrintStream(new File(console.nextLine()));
System.out.println();
String text = input.next();
while (input.hasNext()){
if (text.startsWith("<")){
text = text.substring(1, text.length()-1);
text = text.replace("-"," ");
if ((text.startsWith("a"))||(text.startsWith("e"))||(text.startsWith("i"))||(text.startsWith("o"))||(text.startsWith("u"))){
System.out.print ("Please type an " + text + ": ");
text = (console.nextLine());
}else {
System.out.print ("Please type a " + text + ": ");
text = (console.nextLine());
}
}
out.print(text + " ");
text = input.next();
}//ends while loop
out.print(text);
prompt(console);
}
I apologize for any formatting faux pas, again, this is my first programming class.
Thanks for your help
Instead of using
out.print, you may want to useout.println, which does the same thing, but appends a newline character to the end of the line. You can also manually concatenate the newline character (\n) where you wish to insert linebreaks.