Day06-Scanner

Scanner对象

Day06-Scanner

next()

package com.zfb.Scanner;

import java.util.Scanner;

public class Demo01 {
    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);//创建一个扫描器对象
        System.out.println("使用next的方式接收:");

        //判断用户有没有输入字符串
        if(scanner.hasNext()){
            //使用next方式接收
            String str = scanner.next();//程序会等待用户输入完毕
            System.out.println("输入的内容为"+str);
        }
        //凡是属于IO流的类如果不关闭会一直占用资源,要养成好习惯用完就关掉
        scanner.close();
    }
}

Day06-Scanner

nextLine()

package com.zfb.Scanner;

import java.util.Scanner;

public class Demo02 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("使用nextLine的方式接收:");

        if(scanner.hasNextLine()){
            String str = scanner.nextLine();
            System.out.println("输入的内容为"+str);

        }
        scanner.close();
    }
}

Day06-Scanner

next和nextLine区别

Day06-Scanner

Scanner进阶使用

package com.zfb.Scanner;

import java.util.Scanner;

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

        int i = 0;
        float f = 0.0f;
        System.out.println("请输入整数:");

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

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

        if(scanner.hasNextFloat()){
            f = scanner.nextFloat();
            System.out.println("小数数据:" + f);
        }else{
            System.out.println("输入的不是小数数据!");
        }

        scanner.close();
    }
}

Day06-Scanner
Day06-Scanner

案例

package com.zfb.Scanner;

import java.util.Scanner;

public class Demo04 {
    public static void main(String[] args) {
        //我们可以输入多个数字,并求其总和和平均数,每输入一个数字用回车键确认,通过输入非数字来结束输入并输出执行结果
        Scanner scanner = new Scanner(System.in);
        double sum = 0;//和
        int m = 0;//计算输入了多少个数字
        while (scanner.hasNextDouble()){
            double x = scanner.nextDouble();
            m++;
            sum = sum + x;
        }
        System.out.println(m+"个数的和为"+sum);
        System.out.println(m+"个数的平均值为"+(sum/m));

        scanner.close();
    }

}

Day06-Scanner

上一篇:Java-day06-Debug&基础练习


下一篇:JavaWeb_Day06