nextInt和nextLine以及next方法的区别

最近在刷算法题的时候,发现如下问题

1 Scanner in = new Scanner(System.in)
2 
3 int n = in.nextInt();
4 
5 String str = in.nextLine();

在控制台中,输入:

3

hello

发现str的值为空,说明nextLine方法,没有读取到"hello"字符串。

为了解决以上问题,现将控制台输入内容的读取方法总结下。

一、nextInt()

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

  只读取整形的数据,输入读取完之后,将光标放在同一行。

  换句话说,当我们使用该方法时,会将光标放在读取数字后面,并且是同一行。

二、nextLine()

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

  读取空格,直到以' '为标志的行尾。一旦输入读取完毕,该方法会将光标移到下一行开始的位置。

三、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 line after reading the input.

  读取输入内容直到遇到空格。它不能读取两个字符之间的空格。同时将光标放在读取输入后面,并且在同一行。

四、实验

  1、实验一

  

 1 public class Test {
 2     public static void main(String[] args) {
 3         Scanner in = new Scanner(System.in);
 4         int n = in.nextInt();
 5         while(n>0){
 6             String test = in.nextLine();
 7             System.out.println("test is :"+test );
 8             n--;
 9         }
10     }
11 }

  查看输入输出:

  

  解释:

  输入:"2回车"

  输出:"test is :"

  第一步:输入2回车后,in.nextInt()读取整形数字2,并将光标移到"2"和"回车"之间

  第二步:接下来,in.nextLine()将读取”回车"内容,因为在控制台中不能显示,所以其内容为空

  第三步:输入hello后,in.nextLine()方法读取hello方法


  

  输入:"2 a b回车"

  输出:"test is : a b"

  输入:"hello回车"

  输出:"test is :hello"

  解释:

  第一步:in.nextInt()方法将光标移动到"2"和“空格a空格b回车”之间;

  第二步:in.nextLine()方法读取光标之后的内容,即“空格a空格b回车”

  第三步:输入"hello回车",in.nextLine()方法读取"hello回车内容",并输出"this is:hello"


  2、实验二

  

 1 public class Test {
 2     public static void main(String[] args) {
 3         Scanner in = new Scanner(System.in);
 4         int n = in.nextInt();
 5         while(n>0){
 6             String test = in.next();
 7             System.out.println("test is :"+test);
 8             n--;
 9         }
10 
11     }
12 }

  

  解释:

  第一步:in.nextInt将读入的数字初始化给n,现在光标在"2"和"空格a空格b"之间

  第二步:in.next()方法读取光标之后的"空格a",因为next()不能读取空格,所以遇到第二个空格就停止读取,第一个空格被忽略。此时光标在第二个空格之前

  第三步:读入b

 

  

原文地址:https://www.cnblogs.com/justn0w/p/11143287.html