10、Scanner对象

Scanner对象

image-20210621170626317

1、使用next方式接收

public class UserInputNext {
    public static void main(String[] args) {
        //创建一个扫描器对象,用于接收键盘数据
        Scanner sc = new Scanner(System.in);
        System.out.println("使用next方式接收:");
        //判断用户有没有输入字符串
        if ( sc.hasNext() ) {
            //使用next方式接收
            String str  = sc.next();
            System.out.println("输出的内容为:" + str);
        }
        //凡是属于IO流的类如果不关闭会一直占用资源,要养成好习惯用完就关掉
        sc.close();
    }
}

image-20210621173734758

2、使用nextLine方式接收

public class UserInputNextLine {
    public static void main(String[] args) {
        //从键盘接收数据
        Scanner sc = new Scanner(System.in);
        System.out.println("使用nextLine方式接收:");
        //判断是否还有输入
        if ( sc.hasNextLine() ) {
            String str = sc.nextLine();
            System.out.println("输出的内容为:" + str);
        }
        sc.close();
    }
}

image-20210621173816929

3、next和nextLine的不同

image-20210621173419287

4、通用版

public class UserInput {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入数据:");
        String str = sc.nextLine();
        System.out.println("输出的内容为:" + str);
        sc.close();
    }
}

image-20210621174116513

5、进阶使用

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

        int i = 0;
        double d = 0.0;
        System.out.println("请输入一个整数:");

        if ( sc.hasNextInt() ) {
            i = sc.nextInt();
            System.out.println("输出的整数为:" + i);
        } else {
            System.out.println("输入的不是整数");
        }

        System.out.println("请输入一个小数:");

        if ( sc.hasNextDouble() ) {
             d = sc.nextDouble();
            System.out.println("输出的小数为:" + d);
        } else {
            System.out.println("输入不是小数");
        }
                
        sc.close();
    }
}

image-20210622130806927

image-20210622131007547

image-20210622131034150

6、案例

public class Extend {
    public static void main(String[] args) {
        //输入多个数字,求其总和与其平均数,每输入一个数字用回车确认,通过输入非数字来结束输入并输出执行结果
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一个数字,按回车确认");

        //和
        double sum = 0;
        //计算输入了几个数
        int count = 0;

        //通过循环判断是否还有输入,并在里面对每一次进行求和统计
        while ( sc.hasNextDouble() ) {
            double d = sc.nextDouble();
            ++count;
            sum+=d;
        }
        System.out.println(count + "个数的和为:" + sum);
        System.out.println(count + "个数的平均值为:" + (sum/count));
        sc.close();
    }

image-20210622133122260

posted @ 2021-06-26 16:43  多瑞C  阅读(90)  评论(0)    收藏  举报