Scanner.next()与Scanner.nextLine()的讨论

package test;

import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        // test01();
        test02();
    }

    /**
     * 测试next()换行符问题
     *
     * 测试结果:
     *      next()方法在遇到有效字符前所遇到的空格、tab键、enter键都不能当作结束符,next()方法会自动将其去掉,
     *      只有当next()方法遇到有效字符之后,next()方法才将其后输入的空格键、Tab键或Enter键等视为分隔符或结束符,结束符会留在缓存中
     */
    private static void test01() {
        Scanner sc = new Scanner(System.in);
        String str1 = sc.next();
        System.out.println("str1:"+str1);
        String str2 = sc.next();
        System.out.println("str2:"+str2);
        String str3 = sc.nextLine();
        System.out.println("str3:"+str3);
        sc.close();
    }

    /**
     * 测试nextLine()换行符问题
     *
     * 测试结果:
     *      nextLine()会把换行符吃掉
     *
     */
    private static void test02() {
        Scanner sc = new Scanner(System.in);
        String str1 = sc.nextLine();
        System.out.println("str1:"+str1);
        String str2 = sc.nextLine();
        System.out.println("str2:"+str2);
        int int1 = sc.nextInt();
        System.out.println("int1:"+int1);
        sc.close();
    }
}

原文地址:https://www.cnblogs.com/doubest/p/12597301.html