[英]Java; Line breaks from input text file to output text file
首先,這是我參加的第一門編程課,因此,如果這是一個非常簡單的問題,我深表歉意。 對於家庭作業,我們必須編寫一個程序,該程序掃描文本文件,提示用戶輸入由<>標識的單詞,然后將結果寫入另一個文本文件。
我遇到的問題是輸出文件全部寫在一行上,而不是保留輸入文件中的換行符。
例如:
輸入
看起來像
本文。
輸出看起來像這樣的文本。
這是我在相關方法中的代碼。
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);
}
我為任何格式的設置致歉,這是我的第一門編程課。
謝謝你的幫助
除了使用out.print
,您可能希望使用out.println
,它執行相同的操作,但是在行的末尾附加一個換行符。 您也可以在希望插入換行符的位置手動連接換行符( \\n
)。
是的,喬納森的答案會起作用。 所以我投票支持喬納森。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.