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


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

你可能感兴趣的:(2018-3-8记录关于next(),nextInt(),nextLine()的疑惑与理解)