2018-3-8记录关于next(),nextInt(),nextLine()的疑惑与理解

import java.util.Scanner;

public class Solution {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        
        int i = scan.nextInt();
        double d=scan.nextDouble();
        String s=scan.nextLine();
        System.out.println("String: " + s);
        System.out.println("Double: " + d);
        System.out.println("Int: " + i);
    }
}

这是我开始准备的一段代码,当我输入
42
3.1415
Welcome to  Java!

会发现:输出的是

String: 
Double: 3.1415
Int: 42

为什么

String s=scan.nextLine();

这段代码看上去并没有执行呢?其实不然。让我们先看下一下next()方法、nextInt()方法、nextLine()方法的解释

nextInt(): it only reads the int value, nextInt() places the cursor in the same line after reading the input.

next(): read the input only till the space. It can't read two words separated by space. Also, next() places the cursor in the same lineafter reading the input.

nextLine():  reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.

在代码中double d=scan.nextDouble();并没有完全读取,仅仅读取的是double数值部分,剩下的数值后面的“\n”部分没有读取,因此,当我String s=scan.nextLine();开始的时候读取的是就是double剩下的数值后面的“\n”部分,那我们要如何去避免这种“排队现象”呢?
        double d=scan.nextDouble();
        String s=scan.nextLine();

其实很简单,如果想读取一行,那么我们就先把double后的空白部分读取出来,在double d=scan.nextDouble();后再添加一行代码,scan.nextLine();

public class mmm {
public static void main(String[] args) {
	Scanner sc=new Scanner(System.in);
	int i=sc.nextInt();
	
	double d=sc.nextDouble();
	sc.nextLine();
	String s=sc.nextLine();
	System.out.println("String: " + s);
    System.out.println("Double: " + d);
    System.out.println("Int: " + i);
}
}

输出结果:

42

3.1313

welcome to java

String: welcome to java

Double: 3.1313

Int: 42


个人理解,如有不足请指正,感谢!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值