使用Scanner连续读取整数和字符串时需要注意一下
需要注意的是,如果在通过nextInt()读取了整数后,再接着读取字符串,读出来的是回车换行:”\r\n”,因为nextInt仅仅读取数字信息,而不会读取回车换行”\r\n”.
所以,如果在业务上需要读取了整数后,接着读取字符串,那么就应该连续执行两次nextLine(),第一次是取走回车换行,第二次才是读取真正的字符串
import java.util.Scanner;
public class HelloWorld {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int i = s.nextInt();
System.out.println("读取的整数是"+ i);
String rn = s.nextLine(); // 读取换行符
String a = s.nextLine();
String b = s.nextLine(); // 获得a b两个字符串
System.out.println("读取的字符串是:"+a);
}
}