Scanner類
如果程式能在執行期間互動地從使用者輸入中讀取資料,就可使程式每執行一次時計算出新結果,并且新結果取決于輸入資料。這樣的程式才具有實用性。
Scanner類屬于 Java API,可提供一些友善的方法用于互動式讀取不同類型的輸入資料。輸入可以來自于不同的資料源,包括使用者鍵入的資料或儲存在檔案中的資料。Scanner類還可以用于将一個字元串解析為若幹個子串。圖27列舉了由 Scanner類提供的部分方法。

重點概念:Scanner類提供了一些從不同資料源讀取各種類型資料的方法。
首先必須建立 Scanner類對象,以便引用其方法。在Java中用new運算符建立對象。下面的明建立一個從鍵盤讀取輸入資料的 Scanner類對象
Scanner = scan new Scanner(System. in)
//********************************************************************
// Echo.java Author: Lewis/Loftus
//
// Demonstrates the use of the nextLine method of the Scanner class
// to read a string from the user.
//********************************************************************
import java.util.Scanner;
public class Echo
{
//-----------------------------------------------------------------
// 從使用者處讀取字元串并列印。
//-----------------------------------------------------------------
public static void main(String[] args)
{
String message;
Scanner scan = new Scanner(System.in);
System.out.println("Enter a line of text:");
message = scan.nextLine();
System.out.println("You entered: \"" + message + "\"");
}
}