nextLine方法的回车问题

随笔,今天写代码遇到的问题

        Scanner reader =new Scanner(System.in);
        int b=reader.nextInt();
        String str=reader.nextLine();
        System.out.println("here");
        int a=reader.nextInt();
        System.out.println(b+str+a);

运行结果,输入b为1回车后自动输出here,回车被nextLine当做结束符,nextLine获得的为空白:
1
here
2
12

进程完成,退出码 0

解决方法:
①next()方法代替
② 加一个额外的nextLine。

        Scanner reader =new Scanner(System.in);
        int b=reader.nextInt();
        reader.nextLine();
        String str=reader.nextLine();
        System.out.println("here");
        int a=reader.nextInt();
        System.out.println(b+str+a);

运行结果:
1
2
here
3
123

进程完成,退出码 0

搜到的这篇博文写的清楚点
(https://blog.csdn.net/SummerJX/article/details/79872140)
2019.4.22 补充

import java.util.*;
public class test{
    public static void main(String[] args){
        Scanner reader=new Scanner(System.in);
        for(int i=0;i<3;i++){
            String str=reader.nextLine();
            System.out.println(i+str);
        }


    }
}

运行结果:

0与

1或

2非
在这个循环过程中就不需要加额外的nextLine()来吞回车,不然会出问题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值