基本语法

Scanner in =new Scanner (System.in);

通过Scanner类的next()与nextLine()方法获取输入的字符串,再读取前还可以进行判断是否输入了数据。

next()

1.一定要读取到有效字符后才可以结束输入

2.对输入有效字符之前遇到的空白,next()方法会自动将其去掉

3.只有输入有效字符后才可以将其后面输入的空白作为分隔符或者结束符

4.next()不能得到带有空格的字符

 Scanner s =new Scanner(System.in);//创建扫描器,扫描对象,
        System.out.println("接受next输入的数据:");
        //判断用户有没有输入数据
        if(s.hasNext()){
            //使用next方法接收
            String str= s.next();
            System.out.println("输出的内容为:"+str);
        }
        //凡是属于IO流的类如果不关闭会一直占用资源,要养成好习惯用完就关掉
        s.close();

next Line()

1.以enter为结束符,next Line()方法返回的是回车之前的所有字符

2.可以获得空格

 public static void main(String[] args) {
        Scanner in=new Scanner(System.in);
        System.out.println("使用Next方法");
        if (in.hasNextLine()){
            String str= in.nextLine();
            System.out.println("输出的内容为:"+str);
        }
        in.close();

双重判断:

 public static void main(String[] args) {
        Scanner in=new Scanner(System.in);

        int i=0;
        float f=0.0f;

        System.out.println("请输入一个整数:");
        if (in.hasNextInt()){
            i=in.nextInt();
            System.out.println("整数数据"+i);
        }else{
            System.out.println("输入的不是一个整数");
        }
        System.out.println("请输入一个浮点数:");
        if (in.hasNextFloat()){
            f=in.nextFloat();
            System.out.println("浮点数"+f);
        }else{
            System.out.println("输入的不是一个浮点数");
        }
        in.close();

案列使用

 //我们可以输入多个数字,并求其总和与平均数,每一个数字用回车确认,通过输入非数字来结束输入并输出,执行结果
        Scanner in=new Scanner(System.in);
        System.out.println("请输入数字:");//提示语

        double sum=0;//总和
        int m=0;//计算输入的数字

        while (in.hasNextDouble()){
            double x= in.nextDouble();
            m++;//计数,后续计算平均数
            sum+=x;//sum=sum+x
        }
        System.out.println(m+"个数的和为:"+sum);
        System.out.println(m+"个数平均数为:"+sum/m);

        in.close();