nextLine()消耗行的技巧

public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // 输入一个整数
        System.out.print("请输入一个数字: ");
        int number = scanner.nextInt();

        // 消耗掉换行符
        scanner.nextLine(); // 这一行很重要,因为 nextInt() 方法不会消耗掉换行符

        // 输入一行字符串
        System.out.print("请输入一行字符串: ");
        String word = scanner.next(); // 使用 next() 读取下一个单词
        String line = scanner.nextLine(); // 使用 nextLine() 读取整行

        // 打印输入的数字和字符串
        System.out.println("您输入的数字是: " + number);
        System.out.println("您使用 next() 读取到的是: " + word);
        System.out.println("您使用 nextLine() 读取到的是: " + line);



    }
运行结果:
请输入一个数字: 
123
请输入一行字符串: 
hello world
您输入的数字是: 123
您使用 next() 读取到的是: hello
您使用 nextLine() 读取到的是:  world

Process finished with exit code 0

主要应用

要求先输入一个数字,再换行输入字符串:
   Scanner sc = new Scanner(System.in);
        System.out.println("请输入一个整数");
        int k =sc.nextInt();
        System.out.println(k);
        sc.nextLine();//吃掉换行
        System.out.println("请输入一个字符串");
        String s = sc.nextLine();
        System.out.println(s);

运行结果:
请输入一个整数
12
12
请输入一个字符串
abc def
abc def
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值