Home > Java > Javagetting Started > What is the function of Scanner class in Java

What is the function of Scanner class in Java

王林
Release: 2020-07-20 17:10:21
forward
4896 people have browsed it

What is the function of Scanner class in Java

介绍:

简单来说,Scanner就是用来获取用户在控制台输入的字符串,也可以获取一个文件中的字符串。

(推荐教程:java入门教程

java.util.Scanner 是 Java5 的特征,一个可以使用正则表达式来解析基本类型和字符串的简单文本扫描器。

使用方法介绍:

1、使用不同的 next 方法将得到的标记转换为不同类型的值,比如说要从获控制台取一个输入字符串中的int类型的数字,使用nextInt。

代码示例:

Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
Copy after login

如果需要从一个名文为numbers件中去获取long 类型的数字。

 Scanner sc = new Scanner(new File("numbers"));
      while (sc.hasNextLong()) {
          long longNumber = sc.nextLong();
      }
Copy after login

(视频教程推荐:java视频教程

2、从带有空格中的字符串中获取指定的内容

比如删去字符串 : 1 fish 2 fish red fish blue fish 中的 fish和空格。

代码示例:

     String input = "1 fish 2 fish red fish blue fish";
// 使用正则匹配的方式获取想要的内容
     Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
     System.out.println(s.nextInt());
     System.out.println(s.nextInt());
     System.out.println(s.next());
     System.out.println(s.next());
// 打开文件之后切记要关闭
     s.close();
Copy after login

完整代码示例:

public static void main( String[] args )
{
    if(args!=null){
        println("命令行参数:");
        for(String s:args){
            println(s);
        }
    }
    Scanner input = new Scanner(System.in);
    print( "input x exist。" );
    String str = null ;
    do{
        println("");
        print(":");
        str = input.next();
        System.out.println("您输入的是:"+str);
    }while(!"x".equalsIgnoreCase(str));
    System.out.println("你输入了\"x\",程序已经退出!");
    input.close(); // 关闭资源
}
 
public static void println(String msg){
    System.out.println( msg );
}
 
public static void print(String msg){
    System.out.print( msg );
}
Copy after login

The above is the detailed content of What is the function of Scanner class in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template