Scanner

Scanner对象

  • 之前学习的语法中,并没有实现程序和人的交互,但是Java给我们提供了这样的一个工具类,可以获取用户的输入,我们可以通过Scanner语法获取用户的输入

  • 基本语法:

    Scanner s=new Scanner(System.in);
    
  • 通过Scanner类的next()和nextLine()方法获取输入的字符串,在读取前,一般需要让hasNext()和hasNextLine()判断是否还有输入的数据

  • next()

  1. 一定要读取到有效字符后才可以结束输入
  2. 对输入有效字符之前遇到的空白,next()会自动将其去掉
  3. 只有输入有效字符后才能将其后面输入的空白作为分隔符或者结束符
  4. next()不能得到带有空格的字符串
  • nextLine()
  1. 以enter为 结束符,也就是说nextLine()方法返回的是输入回车之前的所有字符
  2. 可以过得空白
package com.yyr.base.scanner;

import java.util.Scanner;

public class Demo01 {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        //判断用户有没有输入字符串
        if (sc.hasNext()){
            String s=sc.next();
            System.out.println("输入的字符为"+s);
        }
        //凡是属于io流的如果不关叼会一直占用资源,要养成好习惯用完就关掉
        sc.close();
    }
}

package com.yyr.base.scanner;

import java.util.Scanner;

public class Demo02 {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        if (sc.hasNextLine()){
            String s1=sc.nextLine();
            System.out.println("输入的值是"+s1);
        }
        sc.close();
    }
}

package com.yyr.base.scanner;

import java.util.Scanner;

public class Demo03 {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        System.out.println("请输入一个数字:");
        int a= sc.nextInt();
        System.out.println("你输入的数字为:"+a);
    }
}

posted @ 2022-10-15 22:41  野鬼12  阅读(40)  评论(0)    收藏  举报