一,问题所在
java中Scanner类中nextLine()方法与next()或nextInt()联用时可能出现一个常见的错误,那就是当next()或者nextInt(),nextDouble() 、 nextFloat()用在nextLine的前面时。nextLine会把前者的结束符“换行符”作为字符串读入,进而不需要从键盘输入字符串nextLine已经转向下一条语句执行,问题如下:
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2024
<span style="font-size:18px;">import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int times=0;
String s=" ";
Scanner input=new Scanner(System.in);
times=input.nextInt();
while(--times>=0)
{
s = input.nextLine();
<span style="white-space:pre"> </span>if(s.matches("[a-z_A-Z][a-z_A-Z0-9]{0,}"))
<span style="white-space:pre"> </span>System.out.println("yes");
<span style="white-space:pre"> </span>else
<span style="white-space:pre"> </span>System.out.println("no");
}
input.close();
}
}
</span>
其结果为:
很显然笔者还没有来的及从键盘输入,而nextLine已经接收了转行符向下执行了
二,解决方法
解决的办法是:在每一个 next()、nextDouble() 、 nextFloat()、nextInt() 等语句之后加一个nextLine()语句, 将被next()去掉的Enter结束符过滤掉 ,代码和结果如下:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int times=0;
String s=" ";
Scanner input=new Scanner(System.in);
times=input.nextInt();
input.nextLine();
while(--times>=0)
{
s = input.nextLine();
<span style="white-space:pre"> </span>if(s.matches("[a-z_A-Z][a-z_A-Z0-9]{0,}"))
<span style="white-space:pre"> </span>System.out.println("yes");
<span style="white-space:pre"> </span>else
<span style="white-space:pre"> </span>System.out.println("no");
}
input.close();
}
}
三,原因
next()一定要读取到有效字符后才可以结束输入,对输入有效字符之前遇到的空格键、Tab键或Enter键等结束符,next()方法会自动将其去掉,只有在输入有效字符之后,next()方法才将其后输入的空格键、Tab键或Enter键等视为分隔符或结束符。简单地说,next()查找并返回来自此扫描器的下一个完整标记。完整标记的前后是与分隔模式匹配的输入信息,所以next方法不能得到带空格的字符串。
而nextLine()方法的结束符只是Enter键,即nextLine()方法返回的是Enter键之前的所有字符,它是可以得到带空格的字符串的。或者直接这样写可以
转载地址:http://blog.sina.com.cn/s/blog_6aa93fde01016vqr.html