Java 中输入字符串的多种方式364


在 Java 中,有以下几种方法可以从用户或其他输入源输入字符串:

1. Scanner 类

Scanner 类是用于从各种输入源读取数据的标准 Java 类。要使用 Scanner 输入字符串,可以按照以下步骤操作:
import ;
public class InputString {
public static void main(String[] args) {
Scanner scanner = new Scanner();
("输入字符串:");
String input = ();
("输入的字符串:" + input);
}
}

2. BufferedReader 类

BufferedReader 类也用于从各种输入源读取数据。与 Scanner 类类似,可以使用 BufferedReader 输入字符串:
import ;
import ;
public class InputString {
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader())) {
("输入字符串:");
String input = ();
("输入的字符串:" + input);
} catch (IOException e) {
();
}
}
}

3. console() 方法

console() 方法是 System 类的一个静态方法,它返回一个 Console 对象,可以用来从控制台输入字符串:
import ;
public class InputString {
public static void main(String[] args) {
Console console = ();
if (console != null) {
("输入字符串:");
String input = ();
("输入的字符串:" + input);
}
}
}

4. Swing GUI

如果使用 Swing GUI,可以使用 JTextField 来从用户输入字符串:
import .*;
public class InputString {
public static void main(String[] args) {
JFrame frame = new JFrame("Input String");
(300, 200);
(JFrame.EXIT_ON_CLOSE);

JTextField textField = new JTextField();
(textField);

JButton button = new JButton("获取");
(e -> {
String input = ();
("输入的字符串:" + input);
});
(button);

(true);
}
}

选择最佳方法

选择哪种方法输入字符串取决于具体的情况和偏好。以下是一些准则:
如果需要从控制台输入,Scanner 类或 console() 方法是合适的。
如果需要从文件或其他输入流输入,BufferedReader 类是更好的选择。
如果使用 Swing GUI,可以使用 JTextField。

2024-10-15


上一篇:Java中定义和操作二维数组

下一篇:Java小程序的源代码指南