• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
战神何少
博客园    首页    新随笔    联系   管理    订阅  订阅
Scanner 键盘输入流 nextLine() 和next() 的区别

import java.util.Scanner; public class demo2 { public static void main(String[] args) { //创建一个扫描器对象,用于接收键盘数据 Scanner scanner = new Scanner(System.in); System.out.println("通过next()方法获取键盘输入"); //判断用户有没有输入字符串 if(scanner.hasNext()){ String str = scanner.next(); System.out.println(str);//这里我们输入的hello world,但是只打印了hello } //凡是IO流的类如果不关闭一直会占用资源 scanner.close(); } }

  

import java.util.Scanner;

public class demo1 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("使用nextLine接收用户输入");
        //用if判断用户有没有输入
        if(scanner.hasNextLine()){
            //如果有值输入的话就给str
            String  str = scanner.nextLine();
            System.out.println(str);//这里我们输入的hello world,但是打印了hello  hello world
        }
        scanner.close();



    }
}

next(): 

  • 一定要读取到有效字符后才可以结束输入
  • 对输入有效字符之前遇到的空白,next()方法会自动将其去掉
  • 只有输入有效字符后才将其后面输入的空白作为分隔符或者结束符
  • next() 不能得到带有空格的字符

nextLine():

  • 以回车为结束符也就是说nextLine()方法返回的是输入回车之前的所有字符
  • 可以获得空白

 

posted on 2020-06-18 18:51  战神何少  阅读(205)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3