JAVA 類別 - Scanner

用Scanner class來獲取用戶的輸入

創建Scanner 對象的基本語法:

Scanner s = new Scanner ( System . in ) ;

通過Scanner 類的next() 與nextLine() 方法獲取輸入的字符串

在讀取前我們一般需要使用hasNexthasNextLine判斷是否還有輸入的數據:

使用next 方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
`import java . util . Scanner ;`

public class ScannerDemo { public static void main ( String [ ] args ) { Scanner scan = new Scanner ( System . in ) ;
// 從鍵盤接收數據



// next方式接收字符串
System . out . println ( " next接收:" ) ;
// 判斷是否還有輸入
if ( scan . hasNext ( ) ) { String str1 = scan . next ( ) ;
System . out . println ( " 輸入的數據為:" + str1 ) ;
} scan . close ( ) ;
} }

執行以上程序輸出結果為:

1
2
3
next 接收:
yujuko com
輸入的數據為:yujuko

可以看到com 字符串並未輸出

使用nextLine 方法:

ScannerDemo.java 文件代碼:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import java . util . Scanner ;

public class ScannerDemo { public static void main ( String [ ] args ) { Scanner scan = new Scanner ( System . in ) ;
// 從鍵盤接收數據



// nextLine方式接收字符串
System . out . println ( " nextLine接收:" ) ;
// 判斷是否還有輸入
if ( scan . hasNextLine ( ) ) { String str2 = scan . nextLine ( ) ;
System . out . println ( " 輸入的數據為:" + str2 ) ;
} scan . close ( ) ;
} }

執行以上程序輸出結果為:

1
2
3
nextLine 接收:
yujuko com
輸入的數據為:yujuko com

可以看到com 字符串輸出。

next() 與nextLine() 區別

next():

  • 一定要讀取到有效字符後才可以結束輸入。
  • 對輸入有效字符之前遇到的空白,next() 方法會自動將其去掉。
  • 只有輸入有效字符後才將其後面輸入的空白作為分隔符或者結束符。
  • next() 不能得到帶有空格的字符串。

nextLine():

  • 以Enter為結束符,也就是說nextLine()方法返回的是輸入回車之前的所有字符。
  • 可以獲得空白。
  • 如果要輸入int 或float 類型的數據,在Scanner 類中也有支持,但是在輸入之前最好先使用hasNextXxx() 方法進行驗證,再使用nextXxx() 來讀取:

舉例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import java . util . Scanner ;

public class ScannerDemo { public static void main ( String [ ] args ) { Scanner scan = new Scanner ( System . in ) ;
// 從鍵盤接收數據


int i = 0 ;
float f = 0 .0 f ;
System . out . print ( " 輸入整數:" ) ;
if ( scan . hasNextInt ( ) ) { // 判斷輸入的是否是整數

i = scan . nextInt ( ) ;
// 接收整數
System . out . println ( " 整數數據:" + i ) ;
} else { // 輸入錯誤的信息

System . out . println ( " 輸入的不是整數!" ) ;
} System . out . print ( " 輸入小數:" ) ;
if ( scan . hasNextFloat ( ) ) { // 判斷輸入的是否是小數


f = scan . nextFloat ( ) ;
// 接收小數
System . out . println ( " 小數數據:" + f ) ;
} else { // 輸入錯誤的信息

System . out . println ( " 輸入的不是小數!" ) ;
} scan . close ( ) ;
} }

執行以上程序輸出結果為:

1
輸入整數:12 整數數據:12 輸入小數:1.2 小數數據:1.2

以下例子我們可以輸入多個數字,並求其總和與平均數,每輸入一個數字用回車確認,通過輸入非數字來結束輸入並輸出執行結果:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
ScannerDemo.java 文件代碼:
import java . util . Scanner ;

class ScannerDemo { public static void main ( String [ ] args ) { Scanner scan = new Scanner ( System . in ) ;

double sum = 0 ;
int m = 0 ;

while ( scan . hasNextDouble ( ) ) {


double x = scan . nextDouble ( ) ;
m = m + 1 ;
sum = sum + x ;
} System . out . println ( m + " 個數的和為" + sum ) ;
System . out . println ( m + " 個數的平均值是" + ( sum /

m ) ) ;
scan . close ( ) ;
} }

執行以上程序輸出結果為:

1
12 23 15 21.4 end 4 個數的和為71.4 4 個數的平均值是17.85

Reference: