简体   繁体   English

Java; 从输入文本文件到输出文本文件的换行符

[英]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. 除了使用out.print ,您可能希望使用out.println ,它执行相同的操作,但是在行的末尾附加一个换行符。 You can also manually concatenate the newline character ( \\n ) where you wish to insert linebreaks. 您也可以在希望插入换行符的位置手动连接换行符( \\n )。

yep, Jonathan's answer will work. 是的,乔纳森的答案会起作用。 so i vote for Jonathan's,. 所以我投票支持乔纳森。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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