java语言中的scanner是什么意思用来干嘛

Python013

java语言中的scanner是什么意思用来干嘛,第1张

scanner是一个用于扫描输入文本的新的实用程序。它是以前的StringTokenizer和Matcher类之间的某种结合。

由于任何数据都必须通过同一模式的捕获组检索或通过使用一个索引来检索文本的各个部分。于是可以结合使用正则表达式和从输入流中检索特定类型数据项的方法。这样,除了能使用正则表达式之外,Scanner类还可以任意地对字符串和基本类型(如int和double)的数据进行分析。借助于Scanner,可以针对任何要处理的文本内容编写自定义的语法分析器。例如:

public class NextTest{

  public static void main(String[] args) {

      String s1,s2

      Scanner sc=new Scanner(System.in)

      System.out.print("请输入第一个字符串:")

      s1=sc.nextLine()

      System.out.print("请输入第二个字符串:")

      s2=sc.next()

      System.out.println("输入的字符串是:"+s1+" "+s2)

  }

}

运行结果是:

请输入第一个字符串:home

请输入第二个字符串:work

输入的字符串是:home work

扩展资料:

scanner中关于nextInt()、next()和nextLine()的理解

nextInt(): it only reads the int value, nextInt() places the cursor(光标) in the same line after reading the input.(nextInt()只读取数值,剩下”\n”还没有读取,并将cursor放在本行中)

next(): read the input only till the space. It can’t read two words separated by space. Also, next() places the cursor in the same line after reading the input.(next()只读空格之前的数据,并且cursor指向本行)

next() 方法遇见第一个有效字符(非空格,非换行符)时,开始扫描,当遇见第一个分隔符或结束符(空格或换行符)时,结束扫描,获取扫描到的内容,即获得第一个扫描到的不含空格、换行符的单个字符串。

nextLine(): reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.

nextLine()时,则可以扫描到一行内容并作为一个字符串而被获取到。

public static void main(String[] args) {

//1.声明键盘扫描器

Scanner sc = new Scanner(System.in)

/*

sc.nextLine,接收所有元素包括换行符号,返回字符串类型;

sc.next,接收空格之前的所有元素,返回字符串类型;

sc.nextInt,接收整数类型数字

*/

//2.接收键盘输入的内容

String s = sc.next()

//3.输出键盘输入的内容

System.out.println(s)

//例:模拟用户登录

//创建键盘录入扫描对象

Scanner scanner = new Scanner(System.in)

//请输入您的姓名:

System.out.print("请输入您的姓名:")

//接收用户输入的姓名

String userName = scanner.nextLine()

//请输入您的密码:

System.out.print("请输入您的密码:")

//接收用户输入的密码

String passWord = scanner.nextLine()

//登录

System.out.println("欢迎" +userName+ "用户登录")

}