Java学习简易笔记:Scanner

scanner对象

基本语法

 Scanner s = new Scanner(System.in);
  1. 通过Scanner类的next()与nextLine()方法获取输入的字符串,在读取前我们一般使用 hasNext()与hasNextLine()判断是否还有输入的数据;

  2. next() 和 nextLine()的区别是,next不能得到带有空格的字符,也就是说在对输入有效字符之前遇到的空白,next方法会自动将其去掉

 

Example

  • hasNext()的用法

 if(scanner.hasNext()==true){
             //使用next方式接收
             String str=scanner.next();//程序会等待用户输入
             System.out.println("输入的内容为:"+str);
        }
  • 关闭sanner的方法

     scanner.close()
  • hasNextLine()判断及nextLine()方法获取输入的字符串

     if (scanner.hasNextLine()){
                 String str =scanner.nextLine();
                 System.out.println("输入的内容为:"+str);
            }
     //
     int num1=scanner.nextInt();
posted @ 2021-07-28 17:08  酒一  阅读(50)  评论(0)    收藏  举报