Scanner类记录说明

225 阅读1分钟

Scanner对象是java5中加入的新特性,可以通过该类获取用户的输入

hasNext()和hasNextLine()的区别

  1. hasNext 是以读到有效字符串为结束准则,空白会不读取

2.如果输入的内容之间存在空格,空格会自动过滤掉不读取. 如果读取内容为有效字符串+空格+有效字符串情况,只会读取到空格之前的内容,空格之后内容会过滤掉

hasNextLine则是避免掉这个问题

1.hasNextLine 是以Enter为结束准则,会读取敲击Enter之前所有输入的内容包括空格。

next()和nextLine()的区别

next()会截取空格前的字符 nextLine()会截取全部的字符

package 流程控制;

import java.util.Scanner;

public class ScannerObj {
    public static void main(String[] args) {
        // 创建一个扫描对象,用于接受键盘数据
        Scanner sc = new Scanner(System.in);
        // 判断用户有没有输入字符串
        if(sc.hasNext()){
            // 使用next来获取用户输入的字符串
            // 这个返回空格之前,会把空格作为分割符截取
            String str = sc.next();
            // 判断是否还有输入,是已回车作为主要的
            // String str2 = sc.nextLine();
            System.out.println("用户输入的:"+ str);
        }
        // 凡是io流的都想需要关闭,防止消耗
        sc.close();
    }
}

hasNextInt()和hasNextDouble()等api使用


package 流程控制;

import java.util.Scanner;

public class ScannerObj2 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int i;
        if(sc.hasNextInt()){
            i = sc.nextInt();
            System.out.println("输入的整数:" +  i);
       }else {
            System.out.println("输入的不是整数");
        }
        sc.close();
    }
}
package 流程控制;

import java.util.Scanner;

public class ScannerObj3 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        double sum = 0;
        int m = 0;
        while (sc.hasNextDouble()){
            double b = sc.nextDouble();
            m++;
            sum = sum + b;
        }
        System.out.println("输入个数:"+m);
        System.out.println("平均数:"+ (sum/m));
        sc.close();
    }
}