Java || next()與nextLine()的區別

  • nextLine()方法的結束符只是Enter鍵, 也就是“\r”,即nextLine()方法返回的是Enter鍵之前的所有字符,它是可以得到帶空格的字符串的。
  • next()方法讀取到空白符就結束(空白符;比如空格,回車,tab 等等)

例1:先是nextLine(),再是next()

import java.util.Scanner; 
//Scanner中nextLine()方法和next()方法的區別 
public class ScannerString { 
public static void main(String[] args) { 
Scanner input = new Scanner(System.in);
 
System.out.println("請輸入字符串(nextLine):"); 
String str1 = input.nextLine(); 
System.out.println(str1); 

System.out.println("請輸入字符串(next):"); 
String str = input.next(); 
System.out.println(str);

//綠色字體爲輸入字符串,黑色字體爲輸出
在這裏插入圖片描述

例2:先是next(),再是nextLine()

import java.util.Scanner;
//Scanner中nextLine()方法和next()方法的區別
public class ScannerString {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);

System.out.println("請輸入字符串(next):");
String str = input.next();
System.out.println(str);

System.out.println("請輸入字符串(nextLine):");
String str1 = input.nextLine();
System.out.println(str1);

//綠色字體爲輸入字符串,黑色字體爲輸出
在這裏插入圖片描述

可以發現:

  • 修改順序後遇到的問題就是因爲next()讀取到空白符前的數據時結束了,然後把回車“\r”留給了nextLine();
  • 所以上面nextLine()沒有輸出,不輸出不代表沒數據,是接到了空(回車“/r”)的數據。

參考內容:https://blog.csdn.net/superme_yong/article/details/80543995

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章