简体   繁体   中英

Java; Line breaks from input text file to output text file

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 use out.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.

yep, Jonathan's answer will work. so i vote for Jonathan's,.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM