【Java】next() 和 nextLine() 的用法区别详解


next()

  • 读取到有效字符后才可以结束输入
  • 对输入有效字符之前遇到的空格键、Tab键或Enter键等结束符,next()方法会自动将其去掉
  • 只有在输入有效字符之后,next()方法才将其后输入的空格键、Tab键或Enter键等视为分隔符或结束符


nextLine()

  • nextLine() 方法的结束符只是Enter键,即nextLine()方法返回的是Enter键之前的所有字符
  • 可以得到带空格的字符串的


用法:

  • 测试1:nextLine() 在前,next() 在后,且输入都没有空格
public static void main(String[] args) {
    
    
        Scanner input = new Scanner(System.in);
 
        System.out.println("请输入字符串(nextLine):");
        String str1 = input.nextLine();
        System.out.println(str1);
 
        System.out.println("请输入字符串(next):");
        String str = input.next();
        System.out.println(str);
}

输出结果一样:

在这里插入图片描述

  • 测试2:nextLine() 在前,next() 在后,且输入有空格。
    在这里插入图片描述
    分析:next() 只输出了“曹老板”,后面的"很有钱"并没有输出。这是因为 next() 有效字符后遇到输入的空格键、Tab键或Enter键会自动结束,并且不会读取这些符号。

  • 测试3:将代码中next和nextLine的顺序调整一下

    public static void main(String[] args) {
    
    
        Scanner input = new Scanner(System.in);
 
        System.out.println("请输入字符串(next):");
        String str = input.next();
        System.out.println(str);
 
        System.out.println("请输入字符串(nextLine):");//曹老板很有钱
        String str1 = input.nextLine();
        System.out.println(str1);
    }


运行结果:


在这里插入图片描述

分析:我们发现还没有输入nextLine的字符串,它已经停掉了。这是因为next()在输入有效字符后遇到换行符就结束读取了,并且不会读取换行符。而nextLine() 能够读取空格、换行符、Tab键等,且以换行符为分隔符,所以遇到上次输入遗留下来的换行符读取后就结束。这时输入的是 “\r”,而不是空值。



参考文献:java——Scanner中nextLine()方法和next()方法的区别

猜你喜欢

转载自blog.csdn.net/weixin_44668898/article/details/108602374