sc.nextLine()的吸收Enter问题

前言

   大家都知道next()与nextLine()比较大的区别是用next()不能得到带空格的字符串,而nextLine()可以。


   但是大家在使用next()和nextLine()方法有没有遇到过以下问题,比如:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("请输入第一个字符串:");
        String s1  =  sc.next();
        System.out.print("请输入第二个字符串:");
        String s2  =  sc.nextLine();
        System.out.println(s1);
        System.out.println(s2);
    }
}

       而且nextInt(),nextDouble()等等都会遇到和next()一样的问题,以下例子:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一个整数数字:");
        int s1  =  sc.nextInt();
        System.out.println("请输入一个字符串:");
        String s2  =  sc.nextLine();
        System.out.println(s1);
        System.out.println(s2);
    }
}


     类似原因都是是输入第一个内容摁下回车后导致nextLine()自动接收Enter作为结束符,直接默认将第二个字符串内容置为空。解决方法也很简单,就是输入第二个内容之前提前再使用nextLine()将这个回车符吸收掉,如下:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入第一个字符串:");
        String s1  =  sc.next();
        System.out.println("请输入第二个字符串:");
        sc.nextLine();
        String s2  =  sc.nextLine();
        System.out.println(s1);
        System.out.println(s2);
    }
}

      到此我们可以知道,nextLine()在读取内容的时候,是以读取到Enter结束的,但是它只会返回Enter以前的内容,Enter会被吸收读取但是不会作为内容返回。以下例子:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入第一个字符串:");
        String s1  =  sc.nextLine();
        System.out.println("请输入第二个字符串:");
        String s2  =  sc.nextLine();
        System.out.println(s1);
        System.out.println(s2);
    }
}

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值