对于下面一段代码
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String[] sp = new String[n];
for (int i = 0; i < n; i++) {
sp[i] = sc.nextLine();
}
输入n个字符串,但在输入n-1个时程序就会自动结束
如图片所示
next和nextLine的最显著区别在于nextLine可以读入一整行字符,而next遇到空格字符就会停止
于是我又试了一下几串代码
Scanner sc = new Scanner(System.in);
String s1=sc.nextLine();
String s2=sc.nextLine();
String s3=sc.nextLine();
System.out.println(s1+" "+s2+" "+s3);
Scanner sc = new Scanner(System.in);
String s1=sc.next();
String s2=sc.next();
String s3=sc.next();
System.out.println(s1+" "+s2+" "+s3);
Scanner sc = new Scanner(System.in);
String s1=sc.next();
String s2=sc.nextLine();
String s3=sc.nextLine();
System.out.println(s1+" "+s2+" "+s3);
如上所示,当next和nextline仅使用一个时不会出现问题,但混用就会出现丢失数据的问题
其实不止next,nextInt,nextDouble和nextLine的混合使用也会出现此问题
根据输出结果不难发现,其实丢失的s2的值,“s2”被赋值给了s3,而在next之后的s2数据丢失了
通过查询得知,当next函数输入后会在末尾自动添加一个换行符\r\n,而其后nextLine函数将这个换行符读入导致
对于最先出现的问题:
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
sc.nextLine();
String[] sp = new String[n];
for (int i = 0; i < n; i++) {
sp[i] = sc.nextLine();
}
在nextInt函数后加入一个nextLine函数接受其多出的换行符
问题得到完美解决….next和nextLine函数不要混用,在nextInt等函数后加nextLine函数也要注意其自动添加的换行符