Scanner对象

Scanner对象

实现程序与人的交互 ,我们可以通过Scanner类来回去用户的输入

基本语法:Scanner scanner = new Scanner(System.in)

通过 Scanner 类的 next() 与 nextLine() 方法来获取输入的字符串,在读取前我们一般使用 hasNext() 与 hasNextLine() 来判读是否还有输入的数据

 // 创建一个扫描器 用于接收键盘数据
Scanner scanner = new Scanner(System.in);

 System.out.println("使用next()方式接收");

 // 判度胺用户有没有输入数据
 if(scanner.hasNext()){
     // 使用next()方式接收
     String str = scanner.next();
     System.out.println("输入的内容为:" + str);
 }
 // 凡是属于IO流的类如果不关闭会一直占用资源
 scanner.close();

next() 与 nextLine() 的区别

next()

  1. 一定要读取到有效字符才可以结束输入
  2. 对输入有效字符串之前遇到的空白,next()方法会自动去掉
  3. next() 不能得到带有空格的字符串

nextLine()

  1. 以Enter为结束符,也就是说nextLine()方法返回的是回车之前的所有字符
  2. 可以获得空白

posted on 2024-01-19 16:30  很牛逼的程序员  阅读(2)  评论(0编辑  收藏  举报

导航