gpt4 book ai didi

java - 使用 JOptionPane 接收用户的输入

转载 作者:行者123 更新时间:2023-11-30 05:04:07 24 4
gpt4 key购买 nike

这是我的原始代码,提示用户输入文件名。但是,用户必须在控制台内编写才能工作。

BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter file name: ");
String filename = bf.readLine();
File file = new File(filename);
if (!filename.endsWith(".txt")) {
System.out.println("Usage: This is not a text file!");
System.exit(0);
} else if (!file.exists()) {
System.out.println("File not found!");
System.exit(0);
}

现在我想创建一个 JOptionPane 来提示用户在 Pane 内键入。这是我的代码。

BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
JFrame frame = new JFrame();
Object result = JOptionPane.showInputDialog(frame, "Enter a blog website");
String word2 = (String) result;
word2 = bf.readLine();
File file = new File(word2);
if (!word2.endsWith(".txt")) {
System.out.println("Usage: This is not a text file!");
System.exit(0);
} else if (!file.exists()) {
System.out.println("File not found!");
System.exit(0);
}

还有一些进一步的编码可以接收用户的输入并对其进行处理。但是,创建 joptionpane 后,什么也没有发生。 joptionpane 出来了,但是输入后什么也没有发生。请注意我的错误在哪里?

最佳答案

您在读取该值后将其覆盖。

    Object result = JOptionPane.showInputDialog(null, "Enter a blog website");
String word2 = (String) result;

File file = new File(word2);
if (!word2.endsWith(".txt")) {
System.out.println("Usage: This is not a text file!");
System.exit(0);
} else if (!file.exists()) {
System.out.println("File not found!");
System.exit(0);
}

如果您使用 JOptionPane,则不需要 BufferedReader。

关于java - 使用 JOptionPane 接收用户的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5695104/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com