nextLine跳过输入的解决办法

在java中使用扫描器Scanner时,有一个很有趣的现象:

如果在nextline之前使用了next、nextInt等基本类型(companion)时,会出现不能输入的情况。

例如:

Scanner s = new Scanner(System.in);

String str = s.next();

System.out.println("空一行");

String str2 = s.nextLine();

System.out.println("再空一行");

结果:


 

原因:nextline是逐行输入,于是会自动读取  基本类型  省略掉的“enter”,于是结束读取

解决办法(根据具体情况使用):

方法1:nextLine用在最前

方法2:在nextLine前再建立一个不用的输入值,例如:

String str = s.nextInt();

String notuse = s.nextLine();

String str2 = s.nextLine();

方法3:使用next进行输入

String str = s.nextInt();

String notuse = s.next();

next()和nextLine()的区别:

next方法会忽略所有的空格、tab和回车,直到检测到字符才会开始进行输入,当出现空格、tab时,不会再输入(出现回车时会结束输入)。

nextLine方法会检测一行的输入进行操作,会将空格、tab一起录入。

所以在对空格和tab没有需求的时候,可以使用next方法进行输入。

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("再空一行");


 
原文地址:https://www.cnblogs.com/bkytep/p/9492498.html