2 回答

TA貢獻1784條經驗 獲得超8個贊
首先是代碼,然后是解釋...
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Lesson {
public static void main(String[] args) {
File file = new File("mytext.txt");
try (Scanner input = new Scanner(System.in);
PrintWriter pw = new PrintWriter(file)) {
System.out.println("Enter a text here: ");
String str = input.nextLine();
while (str.length() > 0) {
pw.println(str);
pw.flush();
str = input.nextLine();
}
}
catch (IOException xIo) {
xIo.printStackTrace();
}
System.out.println("Done");
}
}
上面的代碼至少需要 Java 7,因為它使用嘗試資源。 應該關閉,就像應該關閉一樣。試用資源可確保它們已關閉。請注意,如果文件 mytext.txt 不存在,則創建新的文件也會創建該文件,如果該文件已存在,則其內容將被刪除并替換為您輸入的文本。ScannerPrintWriterPrintWriter
之后顯示提示,即在此處輸入文本,用戶輸入一行文本。方法將獲取輸入的所有文本,直到用戶按 Enter 鍵。我再次閱讀了您的問題,當用戶在未鍵入任何文本的情況下按Enter鍵時,程序應退出。當用戶執行此操作時,是一個空字符串,即它的長度為零。這意味著我需要在循環之前分配一個值,因此在循環之前第一次調用方法。nextLine()strstrwhilenextLine()while
在循環中,我將用戶輸入的值寫入文件mytext.txt然后等待用戶輸入另一行文本。如果用戶在未鍵入任何文本的情況下按 Enter 鍵,則長度為零,循環將退出。whilestrwhile
在 Windows 10 上使用 JDK 12 編寫并進行了測試,使用適用于 Java 開發人員的 Eclipse,版本 2019-03。

TA貢獻1783條經驗 獲得超4個贊
為了實現這一點,我們檢查輸入的長度是否>0:
import java.io.*;
import java.util.Scanner;
public class lesson {
public static void main(String[] args) throws IOException {
File file = new File("mytext.txt");
if (file.exists() == false) {
file.createNewFile();
}
PrintWriter pw = new PrintWriter(file);
System.out.println("Enter a text here: ");
String str;
Scanner input = new Scanner(System.in);
while ((str = input.nextLine()).length() > 0) {
//str = input.next();
pw.println(str);
}
pw.close();
System.out.println("Done");
}
}
添加回答
舉報