Java-Scanner类
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); |
测试效果:
控制台输入一个可变长度数组
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("");
}