Scanner用法
1.输入整数、字符串数组
第一行输入 n、m
第二行输入 n个整数
第三行输入 m个字符串
/**
* 第一行输入n,m
* 第二行输入n个整数
* 第三行输入m个字符串
*/
public class MyScanner {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
// 定义数组
int[] arr = new int[n];
String[] str = new String[m];
// int 等基本数据类型的数组,用nextInt(),同行或不用行都可以
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
// String字符串数组,读取next(),以空格划分
for (int i = 0; i < m; i++) {
str[i] = sc.next();
}
sc.close();
}
}
2.输入二维数组
第一行输入 n、m
第二行开始输入二维数组
/**
* 输入二维数组
* 第一行输入n、m
* 第二行开始输入二维数组
*/
public class MyScanner2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int[][] arr = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
arr[i][j] = sc.nextInt();
}
}
sc.close();
}
}
3.输入字符串
输入字符串,用空格隔开
next( ) 和 nextLine( ) 的区别
next( ) :读取到空白停止,在读取输入后将光标放在同一行
nextLine( ) :读取到回车停止,在读取输入后将光标放在下一行
/**
* 输入字符串,空格隔开
*/
public class MyScanner3 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// next() 读取输入直到空格
String s = sc.next();
// nextLine() 读取输入,包括单词之间的空格 和 除回车以外的所有符号
String s1 = sc.nextLine();
sc.close();
}
}
4.输入字符串分割为数组
先用 nextLine( ) 读入字符串,再将字符串分割为字符数组或字符串数组
/**
* 输入字符串分割为数组
*/
public class MyScanner4 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str;
str = sc.nextLine();
char[] c = new char[str.length()];
for (int i = 0; i < str.length(); i++) {
c[i] = str.charAt(i);
}
System.out.println(Arrays.toString(c));
// 以空格分割字符串为数组
String[] s = str.split(" ");
System.out.println(Arrays.toString(s));
}
}
5.换行输入数字和字符串
采用nextLine( ),将光标移到下一行。再继续读入字符串
第一行输入n,
第二行开始输入n行字符串,字符串中包含空格。
/**
* 换行输入数字和字符串(包含空格)
*/
public class MyScanner5 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String[] s = new String[n];
for (int i = 0; i < n; i++) {
String str = sc.nextLine();
s[i] = str;
}
sc.close();
}
}