两者都是以空格作为结束标记!!!
int等基本类型的数组使用sc.nextInt()
Sting类型的使用sc.next()
public class MyScanner {
public static void main(String[] args) {
//创建对象
Scanner sc = new Scanner(System.in);
System.out.println("输入数据:");
//多行输入
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();
}
//调用方法进行操作
TestSc(n, m, arr);
TestStr(str);
System.out.println("Test01 End");
//关闭
sc.close();
}
public static void TestSc(int n, int m, int[] arr) {
System.out.println("数据n:" + n + ", 数据m:" + m);
System.out.println(Arrays.toString(arr));
}
public static void TestStr(String[] str) {
System.out.println(Arrays.toString(str));
}
next:碰到空格停止
nextLine:碰到回车停止
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("输入字符串:");
//next():只读取输入直到空格。
String str = sc.next();
//nextLine():读取输入,包括单词之间的空格和除回车以外的所有符号
String str2 = sc.nextLine();
System.out.println("str:" + str);
System.out.println("str2:" + str2);
//关闭
sc.close();
}
不能用for的情况下
while(sc.hasNext()):循环读取
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNext()) {
int n = sc.nextInt();
String str = sc.next();
Tes(n, str);
}
sc.close();
}
public static void Tes(int n, String str) {
System.out.println("n = " + n);
System.out.println("str = " + str);
System.out.println("str.length = " + str.length());
}