nextLine()与next()默认读入的字符串是不同的。next Line()默认读入一整行的数据,而剩下的next()方法在读入时会自动将空格过滤掉。我在写一个录入系统时先写了nextInt(),后面写了两个nextLine(),但是出现下面这种情况。
两个提示信息同时打印,这就说明影片名已经读入了,但是我并没有输入,原因时读入ID时我写的是nextInt(),由于nextInt()过滤掉了回车键,而回车键被nextLine()读入成为了影片名。
其实不仅nextInt()会出现这种情况,除了nextLine(),剩下的next()、nextDouble()都会出现。
有两种方法可以解决这种问题。
第一种:由于需要大量的输入操作,所以我写了一个输入工具类,专门用来读入操作,修改前代码如下
public class ScannerUtil {
private static Scanner in = new Scanner(System.in);
public static String readString(){
String str = in.nextLine();
return str;
}
}
我在原有基础上增加了判断输入是否为空的语句,如果为空则重新输入,避免读入空字符。
修改后代码如下:
public class ScannerUtil {
private static Scanner in = new Scanner(System.in);
public static String readString(){
String str = null;
while (true) {
str = in.nextLine();
//当输入为空重新读
if(str.length() == 0){
continue;
}
break;
}
return str;
}}
}
第二种方法很简单
在nextInt()后面再加一句in.nextLine()即可。这种方法对next()、nextDouble()同样适用。