天天看點

Java Scanner 類

java.util.Scanner 是 Java5 的新特征,我們可以通過 Scanner 類來擷取使用者的輸入。

下面是建立 Scanner 對象的基本文法:

Scanner s = new Scanner(System.in);

接下來我們示範一個最簡單的資料輸入,并通過 Scanner 類的 next() 與 nextLine() 方法擷取輸入的字元串,在讀取前我們一般需要

使用 hasNext 與 hasNextLine 判斷是否還有輸入的資料:

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();

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

可以看到 com 字元串并未輸出,接下來我們看 nextLine。

// nextLine方式接收字元串

System.out.println("nextLine方式接收:");

if (scan.hasNextLine()) {

String str2 = scan.nextLine();

System.out.println("輸入的資料為:" + str2);

可以看到 com 字元串輸出。

next():

1、一定要讀取到有效字元後才可以結束輸入。

2、對輸入有效字元之前遇到的空白,next() 方法會自動将其去掉。

3、隻有輸入有效字元後才将其後面輸入的空白作為分隔符或者結束符。

next() 不能得到帶有空格的字元串。

nextLine():

1、以Enter為結束符,也就是說 nextLine()方法傳回的是輸入回車之前的所有字元。

2、可以獲得空白。

如果要輸入 int 或 float 類型的資料,在 Scanner 類中也有支援,但是在輸入之前最好先使用 hasNextXxx() 方法進行驗證,再使用 nextXxx() 來讀取:

int i = 0;

float f = 0.0f;

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);

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

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

class RunoobTest {

System.out.println("請輸入數字:");

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));

執行以上程式輸出結果為(輸入非數字來結束輸入):

更多内容可以參考 API 文檔:https://www.runoob.com/manual/jdk11api/java.base/java/util/Scanner.html。