天天看點

Scanner類中nextLine()和next(),nextInt()等等的差別。

寫給自己留個記錄,同時也希望能幫助到你們~

技術交流群:167692269

----------------------

結論;

1.nextLine()是     無論指派與否      都 以回車結束

2.next(),nextInt()等等是      必須指派後   才 以空格或回車結束。(若是沒有指派,則一直不會進行到下一步的讀取。)

實際應用一:

import java.util.Scanner;


public class shiyan08 {

	public static void main(String[] args) {
		
		Scanner sc=new Scanner(System.in);
		
		int n=sc.nextInt();
		int m=sc.nextInt();
		String x=sc.nextLine();
		System.out.println("---"+n+"---");
		System.out.println("---"+m+"---");
		System.out.println("---"+x+"---");
		
	}

}
           

輸入:

4
2
           

輸出:

---4---
---2---
------
           

原因:

輸入4後,回車。4被指派給n。

同時,回車也作為x的結束符,(因為之前4被指派給n),是以x空字元串。

接着,輸入2,回車。2指派給m。

輸出如上。

解決辦法:

public class shiyan08 {

	public static void main(String[] args) {
		
		Scanner sc=new Scanner(System.in);
		
		int n=sc.nextInt();
		sc.nextLine();        //接收一個回車。以防止第一個回車  作為 x 的結束符,使得x被指派為空字元串。  
           
int m=sc.nextInt();  
           

sc.nextLine(); ` //接收一個回車,以防止第二個回車 作為 x的結束符,使得x被指派為空字元串。String x=sc.nextLine();System.out.println("---"+n+"---");System.out.println("---"+m+"---");System.out.println("---"+x+"---");}}

如果需要按到回車時,加一個sc.nextline()接收這個回車符。  以防止 需要用到回車符 (如給 x 指派)時, 之前的回車被錯誤的當成x 的結束标志了。

輸入:

4
2
我終于能輸入了
           

輸出:

---4---
---2---
---我終于能輸入了---
           

實際應用二:

public static void main(String[] args) {
		
		Scanner sc=new Scanner(System.in);
		
		int n=sc.nextInt();
		int m=sc.nextInt();	
		String x=sc.nextLine();
		System.out.println(n+m);
	
		
		

	}
           

輸入:

1 4 56
           

輸出:

5
           

原因:

輸入1後,空格。1被指派給n。

然後4後面又有一個空格,4被指派給了m。

n,m已經接收完畢。是以後面輸入多少都不會被接收了。

是以輸出是5.

--------------

若是有什麼疑問或者新的見解,,歡迎讨論~

技術交流群:167692269