使用Scanner连续读取整数和字符串时需要注意一下

    需要注意的是,如果在通过nextInt()读取了整数后,再接着读取字符串,读出来的是回车换行:”\r\n”,因为nextInt仅仅读取数字信息,而不会读取回车换行”\r\n”.
    所以,如果在业务上需要读取了整数后,接着读取字符串,那么就应该连续执行两次nextLine(),第一次是取走回车换行,第二次才是读取真正的字符串

    1. import java.util.Scanner;
    2. public class HelloWorld {
    3. public static void main(String[] args) {
    4. Scanner s = new Scanner(System.in);
    5. int i = s.nextInt();
    6. System.out.println("读取的整数是"+ i);
    7. String rn = s.nextLine(); // 读取换行符
    8. String a = s.nextLine();
    9. String b = s.nextLine(); // 获得a b两个字符串
    10. System.out.println("读取的字符串是:"+a);
    11. }
    12. }