Scanner实现字符串的输入有两种方法,一种是next(),一种nextLine()。
next():一定要读取到有效字符后才可以结束输入,对输入有效字符之前遇到的空格键、Tab键或Enter键等结束符,next()方法会自动将其去掉,只有在输入有效字符之后,next()方法才将其后输入的空格键、Tab键或Enter键等视为分隔符或结束符。
简单地说:
next()查找并返回来自此扫描器的下一个完整标记。完整标记的前后是与分隔模式匹配的输入信息,所以next方法不能得到带空格的字符串。
nextLine()方法的结束符只是Enter键,即nextLine()方法返回的是Enter键之前的所有字符,它是可以得到带空格的字符串的。
public class NextTest{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("请输入第一个字符串:");
String s1 = input.nextLine();
System.out.print("请输入第二个字符串:");
String s2 = input.next();
System.out.println("输入的字符串是:"+ s1 + " " + s2);
}
}
运行结果:
请输入第一个字符串:home work
请输入第二个字符串:over
输入的字符串是:home work over
注意点(易错点): 注意next()方法和nextLine()方法的连用
如果把上面的程序改一下:
public class NextTest{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("请输入第一个字符串:");
String s1 = input.next();
System.out.print("请输入第二个字符串:");
String s2 = input.nextLine();
System.out.println("输入的字符串是:"+ s1 + " " + s2);
}
}
运行结果是:
请输入第一个字符串:home
请输入第二个字符串:输入的字符串是:home
可以看到,nextLine()自动读取了被next()去掉的Enter作为它的结束符,所以没办法给s2从键盘输入值。经过验证,发现其他的next的方法,如nextDouble() ,nextFloat() ,nextInt() 等与nextLine()连用时都存在这个问题,解决的办法是:在每一个 next()、nextDouble() 、 nextFloat()、nextInt() 等语句之后加一个nextLine()语句,将被next()去掉的Enter等结束符过滤掉。
上面的程序改正为:
public class NextTest{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("请输入第一个字符串:");
String s1 = input.next();
input.nextLine(); //接收结束符
System.out.print("请输入第二个字符串:");
String s2 = input.nextLine();
System.out.println("输入的字符串是:"+ s1 + " " + s2);
}
}
运行结果是:
请输入第一个字符串:home
请输入第二个字符串:work
输入的字符串是:home work