3 回答
TA贡献1809条经验 获得超8个赞
的值System.in
是 的实例InputStream
,是“标准输入”。正如文档所说:
“标准”输入流。该流已打开并准备好提供输入数据。通常,该流对应于键盘输入或主机环境或用户指定的另一个输入源。
当您使用时,new Scanner(System.in)
您正在使用Scanner#<init>(InputStream)
构造函数,其文档说:
构造一个 new
Scanner
来生成从指定输入流扫描的值。使用底层平台的默认字符集将流中的字节转换为字符。
如您所见,传递System.in
只是将其配置Scanner
为从标准输入读取。您当然可以使用InputStream
从其他地方(例如网络、文件等)读取的不同内容。如果您查看其他构造函数,Scanner
您会发现您可以配置许多不同类型的源(例如文件、String
等)。
TA贡献1786条经验 获得超11个赞
因为你需要指定从哪里读取。
以下陈述完全有效并来自各种来源
Scanner sc = new Scanner(new File("myNumbers"));
String input = "1 fish 2 fish red fish blue fish";Scanner s = new Scanner(input);
Scanner sc = new Scanner(System.in);
所以,现在您必须清楚,在实例化 Scanner 对象时System.in
不必总是作为参数。
继续,解释你为什么通过System.in
来自文档
公共扫描仪(InputStream源)
构造一个新的 Scanner,它生成从指定输入流扫描的值。使用底层平台的默认字符集将流中的字节转换为字符。
从java.lang.System
/**
* The "standard" input stream. This stream is already
* open and ready to supply input data. Typically this stream
* corresponds to keyboard input or another input source specified by
* the host environment or user.
*/
public final static InputStream in = null;
希望这是不言自明的!
TA贡献1803条经验 获得超6个赞
来自 Javadoc:类扫描器
| Constructor | Description |
|---------------------------------------------------------|----------------------------------------------------------------------------------------|
| Scanner(File source) | Constructs a new Scanner that produces values scanned from the specified file. |
| Scanner(File source, String charsetName) | Constructs a new Scanner that produces values scanned from the specified file. |
| Scanner(File source, Charset charset) | Constructs a new Scanner that produces values scanned from the specified file. |
| Scanner(InputStream source) | Constructs a new Scanner that produces values scanned from the specified input stream. |
| Scanner(InputStream source, String charsetName) | Constructs a new Scanner that produces values scanned from the specified input stream. |
| Scanner(InputStream source, Charset charset) | Constructs a new Scanner that produces values scanned from the specified input stream. |
| Scanner(Readable source) | Constructs a new Scanner that produces values scanned from the specified source. |
| Scanner(String source) | Constructs a new Scanner that produces values scanned from the specified string. |
| Scanner(ReadableByteChannel source) | Constructs a new Scanner that produces values scanned from the specified channel. |
| Scanner(ReadableByteChannel source, String charsetName) | Constructs a new Scanner that produces values scanned from the specified channel. |
| Scanner(Path source) | Constructs a new Scanner that produces values scanned from the specified file. |
| Scanner(Path source, String charsetName) | Constructs a new Scanner that produces values scanned from the specified file. |
| Scanner(Path source, Charset charset) | Constructs a new Scanner that produces values scanned from the specified file. |
要指定您想要哪种类型的扫描仪,您必须传递一个参数。System.in 告诉 Scanner 类,从InputStream source
添加回答
举报