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 + "\"");
}
}