Scanner input = new Scanner(System.in);
你能详细解释一下上面的代码一步一步做了什么吗?我真的不明白它是如何工作的以及它如何链接到我以后能够做这个声明:
int i = input.nextInt()
最佳答案
好吧,让我们对 Scanner
做一些简单的解释。类。
这是一个标准的 Oracle 类,您可以通过调用 import java.util.Scanner
使用它。
那么让我们做一个类的基本示例:
class Scanner {
InputStream source;
Scanner(InputStream src) {
this.source = src;
}
int nextInt() {
int nextInteger;
//Scans the next token of the input as an int from the source.
return nextInteger;
}
}
现在,当您调用 Scanner input = new Scanner(System.in);
时,您创建了一个 Scanner
类的新对象(因此您创建了一个新的“Scanner” ) 并将其存储在变量 input
中。同时您正在调用(所谓的)constructor类的,带有参数 System.in
。这意味着它将从程序的标准输入流中读取。
现在,当您调用 input.nextInt();
时,您会从刚刚创建的对象(也是 documented)执行该方法。但是正如我们所见,此方法返回一个整数,因此如果我们想使用该整数,我们必须像您一样将调用分配给一个变量:
int i = input.nextInt();
关于java - Scanner input = new Scanner(System.in) 到底是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30612811/