英文:
How Scanner class works in java with input?
问题
Scanner类是一种用于从控制台窗口读取输入的工具。它是逐个读取输入的。
例如:
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
String str = scan.nextLine();
float f = scan.nextFloat();
Scanner会逐个读取输入,它不会一次性获取所有输入然后逐个填充数据成员。每次调用nextInt()
、nextLine()
、nextFloat()
等方法时,Scanner会等待用户在控制台中输入一个值,然后将该值存储在相应的数据成员中。
英文:
Does Scanner take all the input from the console window at once or does it take it one by one?
For example:
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int str = scan.nextLine();
float f = scan.nextFloat();
Does Scanner take all the input at once and then put the value one by one in the data member? Or does it take one input and put its value in the corresponding data member then take another?
答案1
得分: 2
如果您键入7
然后按Enter键,代码将会赋值n = 7
并且str = ""
1,然后会等待更多输入。如果您随后键入3.14
并按Enter键,代码将会赋值f = 3.14
。
当用户按下Enter键时,System.in
将会接收用户输入,所以尽管它是一个字符流(实际上是字节),它们将以一行一行的块到达。
因此,Scanner
也将一次看到一行。
1) 参见 Scanner在使用next()或nextFoo()之后跳过nextLine()吗?
英文:
Both, either, depends.
If you type 7
then press Enter, the code will assign n = 7
and str = ""
<sup>1</sup> and will then wait for more. If you then type 3.14
and press Enter, the code will assign f = 3.14
.
System.in
will receive user input when the user presses Enter, so although it is a stream of characters (bytes actually), they will arrive in blocks of 1 line at a time.
Scanner
will therefore see that 1 line at a time too.
<sup>1) See Scanner is skipping nextLine() after using next() or nextFoo()?</sup>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论