在java中使用掃描器Scanner時(shí),有一個(gè)很有趣的現(xiàn)象:
如果在nextline之前使用了next、nextInt等基本類型(companion)時(shí),會(huì)出現(xiàn)不能輸入的情況。
例如:
Scanner s = new Scanner(System.in);
String str = s.next();
System.out.println("空一行");
String str2 = s.nextLine();
System.out.println("再空一行");
結(jié)果:

原因:nextline是逐行輸入,于是會(huì)自動(dòng)讀取? 基本類型? 省略掉的“enter”,于是結(jié)束讀取
解決辦法(根據(jù)具體情況使用):
方法1:nextLine用在最前
方法2:在nextLine前再建立一個(gè)不用的輸入值,例如:
String str = s.nextInt();
String notuse = s.nextLine();
String str2 = s.nextLine();
方法3:使用next進(jìn)行輸入
String str = s.nextInt();
String notuse = s.next();
next()和nextLine()的區(qū)別:
next方法會(huì)忽略所有的空格、tab和回車,直到檢測(cè)到字符才會(huì)開始進(jìn)行輸入,當(dāng)出現(xiàn)空格、tab時(shí),不會(huì)再輸入(出現(xiàn)回車時(shí)會(huì)結(jié)束輸入)。
nextLine方法會(huì)檢測(cè)一行的輸入進(jìn)行操作,會(huì)將空格、tab一起錄入。
所以在對(duì)空格和tab沒有需求的時(shí)候,可以使用next方法進(jìn)行輸入。
String s1 = s.next();
System.out.println("空一行");
System.out.println(s1);
String notuse = s.nextLine();
String s2 = s.nextLine();
System.out.println(s2);
System.out.println("再空一行");
