Java基础之Scanner类中next()与nextLine()方法的区别

本文介绍了 Java 中 Scanner 类的 next() 和 nextLine() 方法的区别。next() 方法读取不含空格和换行符的单个单词,而 nextLine() 方法则读取整个行作为字符串。通过示例代码演示了两种方法的行为差异。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

java中使用Scanner类实现数据输入十分简单方便,Scanner类中next()与nextLine()都可以实现字符串String的获取,所以我们会纠结二者之间的区别。

其实next()与nextLine()区别很明确:

next() 方法遇见第一个有效字符(非空格,非换行符)时,开始扫描,当遇见第一个分隔符或结束符(空格或换行符)时,结束扫描,获取扫描到的内容,即获得第一个扫描到的不含空格、换行符的单个字符串。
使用nextLine()时,则可以扫描到一行内容并作为一个字符串而被获取到。
举例说明一下:
import java.util.Scanner;

public class ScannerTest {
    
    public static void main(String[] args) {
        System.out.println("---->Test1:");
        Scanner scanner = new Scanner(System.in);
        String nextStr = scanner.next();
        System.out.println("scanner.next()得到:" + nextStr);
        String nextlineStr = scanner.nextLine();
        System.out.println("scanner.nextLine()得到:" + nextlineStr);
        
        System.out.println("\n---->Test2:");
        String nextlineStr2 = scanner.nextLine();
        System.out.println("scanner.nextLine()得到:" + nextlineStr2);
        String nextStr2 = scanner.next();
        System.out.println("scanner.next()得到:" + nextStr2);
    }
}

运行以上代码得到(我每次都是输入Hello World Nice To See You):

注意:--->Test2:处的第一个scanner.next()改为scanner.nextLine().


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值