Java-Scanner类

Java Scanner类

  • 用于获取用户输入 语法:

    Scanner s = new Scanner(System.in);

  • 可通过调用下列函数nextDouble()nextFloatnextInt()nextLine()nextLong()nextShot()读取用户在命令行输入的各种数据类型 

  • next()与nextLine()区别:

    • next() :
    1. 一定要读到有效字符结束输入
    2. 对输入有效字符之前遇到的空白,next() 方法会自动将其去掉。
    3. 只有输入有效字符后才将其后面输入的空白作为分隔符或者结束符。
    4. next() 不能得到带有空格的字符串。 总之就是遇到空格停止扫描
    • nextLine():
    1. 以Enter为结束符,也就是说 nextLine()方法返回的是输入回车之前的所有字符。
    2. 可以获得空白。 总之就是以回车为停止扫描

举例:

Scanner sc = new Scanner(System.in);
System.out.println("输入:");
String s = sc.next();//Hello World!
System.out.println(s);
测试效果: 在这里插入图片描述

Scanner sc = new Scanner(System.in);
System.out.println("输入:");
String s = sc.nextLine();//Hello World!
System.out.println(s);

测试效果: 在这里插入图片描述

  • 控制台输入一个可变长度数组

    Scanner sc = new Scanner(System.in);
    String[] strArray = null;
    strArray = sc.nextLine().split("\\s*,\\s*"); // ','分割,前后可以有空格
    int[] intArray = new int[strArray.length];

    for(int i = 0; i< strArray.length; i++) {
    intArray[i] = Integer.parseInt(strArray[i]);
    }

  • 控制台输入一个二维数组

    Scanner sc = new Scanner(System.in);
    System.out.print("二维数组的行数:");
    int r = sc.nextInt();
    System.out.println("二维数组的列数:");
    int c = sc.nextInt();
    int[][]matrix = new int[r][c];
    sc.nextLine();//用来跳过行列后的回车符
    for(int i = 0; i < r; i++){
    for(int j = 0; j < c; j++){
    matrix[i][j] = sc.nextInt();
    System.out.print(matrix[i][j] + ",");
    }
    System.out.println("");
    }
    测试效果: 在这里插入图片描述

------ 本文结束感谢您的阅读 ------