Scanner 用户交互

Scanner基础用法

next 和nextline区别

next用法

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();
    }
}

运行结果:

使用next来接收
 hello world
输出的内容为:hello
  • 一定要读取到有效字符后才可以结束输入
  • 对有效字符之前遇到的空白,next()方法会自动将其去掉
  • 只有输入有效字符后才将其后面输入的空白作为分隔符或者结束符
  • next()不能得到带有空格的字符串

nextLine用法

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.hasNext()){

            String str = scanner.nextLine();
            System.out.println("输出的内容为:"+str);

        }
    }
}

运行结果:

使用nextline来接收
hello world
输出的内容为:hello world
  • 以Enter为结束符,也就是说nextLine()方法返回的是输入回车之前的所有字符
  • 可以获得空白

Scanner进阶使用

输入多个数字,求和以及平均值,每输入一个值用回车确认,直至输入非数字来结束输入

public class Demo04 {
    public static void main(String[] args) {
        //输入多个数字,求和以及平均值,每输入一个值用回车确认,直至输入非数字来结束输入
        Scanner scanner = new Scanner(System.in);
        double sum = 0.0;   //和
        int c = 0;          //输入个数

        while (scanner.hasNextDouble()) {
            //每个输入的值
            double x = scanner.nextDouble();
            c++;
            sum += x;
            System.out.println("你输入了第"+c+"个数据,当前的和是:"+sum);
        }
        System.out.println("和为:" + sum);
        System.out.println("平均值为:" + (sum / c));

        scanner.close();
    }
}
posted @ 2021-01-28 16:06  杪夏九  阅读(96)  评论(0)    收藏  举报