我需要做以下练习: a) 新建一个文本文件 b) 将用户的输入放入该文本文件 c) 我们必须在用户继续输入时保存所有用户的输入,但是只要用户在新行中按 Enter(发送空字符串时),用户就必须退出程序。 为了对这个问题进行编码,我编写了以下代码,但是当 我自己尝试,所以我陷入了 while 循环,当我发送空字符串时无法退出。 那么有人可以帮助解决这个问题吗?
谢谢
我已经尝试了一些我在 youtube 上找到的解决方案,例如在 while 循环内制作 if 语句或添加在循环条件内接受用户输入的代码。 所以我不知道下一阶段要做什么。 我试图通过 Eclipse 输出查看控制台窗口。
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;
while (true) {
Scanner input = new Scanner(System.in);
str = input.next();
pw.println();
if (str.equals(null)) {
break;
}
}
pw.close();
System.out.println("Done");
}
}
当用户发送一个空字符串时,他/她必须跳出循环。并且必须完成对文件的写入。
最佳答案
先是代码,再是解释...
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,因为它使用了 try-with-resources . Scanner
应该关闭,就像 PrintWriter
应该关闭一样。 try-with-resources 确保它们是关闭的。请注意,如果文件 mytext.txt 不存在,创建一个新的 PrintWriter
也会创建该文件,如果该文件已经存在,其内容将被删除并替换为您输入的文本。
之后显示提示,即在此处输入文本,然后用户输入一行文本。方法 nextLine()
将获取所有输入的文本,直到用户按下 Enter。我再次阅读了您的问题,当用户按 Enter 而不键入任何文本 时,程序应该退出。当用户这样做时,str
是一个空字符串,即它的长度为零。这意味着我需要在 while
循环之前为 str
赋值,因此在 之前第一次调用方法
循环。nextLine()
while
在 while
循环中,我将用户输入的值写入文件 mytext.txt,然后等待用户输入另一行文本。如果用户在没有输入任何文本的情况下按下 Enter,str
的长度将为零,while
循环将退出。
使用 JDK 12 在 Windows 10 上使用 Eclipse 编写和测试适用于 Java 开发人员,版本 2019-03。
关于java - 当用户在新行中按回车键时,他/她必须退出 while 循环。但它不起作用,它一直在换行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55514637/