Scanner

Scanner

  1. Scanner类可以获取用户的输入 java.util.Scanner 是java5的新特性
  2. 基本语法
  3. 通过Scanner 类的next()和nextLine()方法获取输入的字符串,在读取前我们一般需要使用hasNext()与hasNextLine()判断是否还有输入的数据

示例

1.next()

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("please input string:"); // hello world
    if (scanner.hasNext()) {
        String s = scanner.next();
        System.out.println("your input is:" + s); // hello
    }
    scanner.close();

}

2.nextLine()

public static void main(String[] args) {

    Scanner scanner = new Scanner(System.in);
    System.out.println("please input string:"); // hello world
    if (scanner.hasNextLine()) {
        String s = scanner.nextLine();
        System.out.println("your input is:" + s); // hello world
    }
    scanner.close();
}

3.nextDouble()

public static void main(String[] args) {
    // 输入数字,以回车分隔,求平均数
    Scanner scanner = new Scanner(System.in);
    double sum = 0;
    int i = 0;
    while (scanner.hasNextDouble()) {
        sum += scanner.nextDouble();
        i++;
    }
    System.out.println("sum =" + sum);
    System.out.println("i =" + i);
    System.out.println("average =" + sum / i);
    scanner.close();
}
posted @ 2021-10-21 09:08  Oh,mydream!  阅读(75)  评论(0编辑  收藏  举报