Java中關於nextInt()、next()和nextLine()的理解

先看解釋:java

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

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.code

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.blog

看完以後nextInt()、next()和nextLine()的區別已經很清楚了,我以爲最容易出錯的就是cursor問題。ci

看下面代碼:input

 1 import java.util.Scanner;
 2 
 3 public class MaxMap {
 4     public static void main(String[] args){
 5         Scanner cin = new Scanner(System.in);
 6         int n = cin.nextInt();
 7         String str = cin.nextLine();
 8         System.out.println("END");
 9         }
10 }            

執行後結果:it

從執行結果上看,貌似直接跳過了String str = cin.nextLine();這行代碼。io

其實否則,緣由是:nextInt()只讀取數值,剩下"\n"尚未讀取,並將cursor放在本行中。nextLine()會讀取"\n",並結束(nextLine() reads till the end of line \n)。class

若是想要在nextInt()後讀取一行,就得在nextInt()以後額外加上cin.nextLine(),代碼以下import

import java.util.Scanner;

public class MaxMap {
    public static void main(String[] args){
        Scanner cin = new Scanner(System.in);
        int n = cin.nextInt();
        cin.nextLine();
        String str = cin.nextLine();
        System.out.println("END");
        }
}

在看下面代碼:

 1 import java.util.Scanner;
 2 
 3 public class MaxMap {
 4     public static void main(String[] args){
 5         Scanner cin = new Scanner(System.in);
 6         String n = cin.next();
 7         //cin.nextLine();
 8         String str = cin.nextLine();
 9         System.out.println("END");
10         System.out.println("next()read:"+n);
11         System.out.println("nextLine()read:"+str);
12     }
13 }

執行結果:

 緣由:next()只讀空格以前的數據,而且cursor指向本行,後面的nextLine()會繼續讀取前面留下的數據。

    想要讀取整行,就是用nextLine()。

    讀取數字也能夠使用nextLine(),不過須要轉換:Integer.parseInt(cin.nextLine())。

注意在next()、nextInt()與nextLine()一塊兒使用時,next()、nextInt()每每會讀取部分數據(會留下"\n"或者空格以後的數據)。

相關文章
相關標籤/搜索