Java Scanner类
- 用于获取用户输入
语法:Scanner s = new Scanner(System.in);
- 可通过调用下列函数nextDouble(),nextFloat,nextInt(),nextLine(),nextLong(),nextShot()读取用户在命令行输入的各种数据类型
- next()与nextLine()区别:
- next() :
- 一定要读到有效字符结束输入
- 对输入有效字符之前遇到的空白,next() 方法会自动将其去掉。
- 只有输入有效字符后才将其后面输入的空白作为分隔符或者结束符。
- next() 不能得到带有空格的字符串。
总之就是遇到空格停止扫描
- nextLine():
- 以Enter为结束符,也就是说 nextLine()方法返回的是输入回车之前的所有字符。
- 可以获得空白。
总之就是以回车为停止扫描
举例:
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(""); }
测试效果:
-
当输入类型有多种时,先全部输入String类型,使用split()方法进行分割,变为String[]类型,再将每部分转换为相应格式。
Scanner sc = new Scanner(System.in); String str1 = sc.nextLine(); String str2 = sc.nextLine(); String[] num = str1.split(" "); int N = Integer.parseInt(num[0]); int M = Integer.parseInt(nums[1]); Stirng[] ff = str2.split(" "); float[] nums = new float[N]; for(int i = 0; i < N; i++){ nums[i] = Float.parseFloat(ff[i]); }