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 \n). Once the input is read, nextLine() positions the cursor in the next line.

  讀取空格,直到以'\n'為標志的行尾。一旦輸入讀取完畢,該方法會將光標移到下一行開始的位置。

三、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

 

 

 

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM