4.8 阅读文档

Java 的优点之一是自带了庞大的类库和方法。但在使用之前,可能还必须阅读文档,而这并非总是那么容易。

例如,咱们来看看 3.2 节中使用的 Scanner 类文档。要找到这个文档,可在网上搜索 Java Scanner,图 4-2 是该文档页面的屏幕截图。

{%}

图 4-2:Scanner 文档的屏幕截图

其他类的文档格式与此类似。第 1 行是类所属的包,如 java.util;第 2 行是类名。截屏中的 All Implemented Interfaces 列举了部分 Scanner 能够做的事情,这里不打算做更深入的介绍。

文档的下一部分是描述,阐述了当前类的用途,还包含了使用示例。这些内容可能难以理解,因为其中使用了你还没有学过的术语,但其中的示例经常很有用。要开始使用新类,一种不错的方式是将文档中的示例粘贴到测试文件中,看看它们能否编译并运行。

有个示例演示了如何用 ScannerString 而不是 System.in 读取输入:

  1. String input = "1 fish 2 fish red fish blue fish";
  2. Scanner s = new Scanner(input);

描述、代码示例和其他细节的后面是以下几个表格:

  • Constructor summary

创建或构造 Scanner 对象的方式

  • Method summary

Scanner 提供的方法列表

  • Constructor detail

更多与 Scanner 对象创建方式有关的信息

  • Method detail

有关各个方法的详细信息

例如,下面是 nextInt 的摘要信息:

  1. public int nextInt()
  2. Scans the next token of the input as an int.

第 1 行是方法的特征标(signature),它指定了方法的名称、形参(无)和返回类型(int);第 2 行简单地描述了这个方法的功能。

表格 Method detail 更详细地阐述了这个方法:

  1. public int nextInt()
  2. Scans the next token of the input as an int.
  3. An invocation of this method of the form nextInt() behaves in
  4. exactly the same way as the invocation nextInt(radix), where
  5. radix is the default radix of this scanner.
  6. Returns:
  7. the int scanned from the input
  8. Throws:
  9. InputMismatchException - if the next token does not match
  10. the Integer regular expression, or is out of range
  11. NoSuchElementException - if input is exhausted
  12. IllegalStateException - if this scanner is closed

其中的 Returns 部分描述了这个方法成功时返回的结果,而 Throws 部分描述了可能发生的错误及其引发的异常。

要想熟练地阅读文档并就哪些部分可以忽略作出准确的判断,可能需要一段时间的学习,但这样的付出是值得的。知道 Java 库有哪些类可避免重复劳动,只需阅读少量的文档就可避免繁重的调试工作。