首页 > java笔记 > Java Scanner用法介绍

Java Scanner用法介绍

更新:

Java Scanner是一个提供文本扫描功能的类,我们可以用它来解析基本类型和字符串。

一、Scanner的创建和基本使用

我们可以通过各种方式创建Scanner对象,如System.in,File,String等。以下是一些示例:

Scanner scanner = new Scanner(System.in);
Scanner scanner = new Scanner(new File("fileName.txt"));
Scanner scanner = new Scanner("Hello World!");

使用Scanner对象,我们可以获取输入的基本类型数据和字符串,如nextInt(),nextLine()等。

int i = scanner.nextInt();
String s = scanner.nextLine();

二、Scanner的特性和注意事项

Scanner的强大之处在于其灵活的模式匹配,我们可以通过useDelimiter设置分隔符。

Scanner scanner = new Scanner("Hello World!");
scanner.useDelimiter("[ ,.!?]+");
while (scanner.hasNext()) {
    System.out.println(scanner.next());
}

在使用Scanner时,需要注意的是,当我们同时使用nextLine和其他nextXxx方法时,可能会出现输入错误,因为nextLine方法会读取换行符。

Scanner scanner = new Scanner(System.in);
int i = scanner.nextInt();
String s = scanner.nextLine();  // This will get an empty string because nextInt() does not consume newline character

三、Scanner的关闭

为了防止资源泄露,我们应该在使用完Scanner后关闭它。但如果Scanner是基于System.in创建的,那么我们不应该关闭它,因为这会关闭标准输入。

Scanner scanner = new Scanner(new File("fileName.txt"));
while (scanner.hasNext()) {
    System.out.println(scanner.next());
}
scanner.close();
顶部