Scanner类在java中的工作原理以及输入方式是怎样的?

huangapple go评论86阅读模式
英文:

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 = &quot;&quot;<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>

huangapple
  • 本文由 发表于 2020年9月24日 11:03:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/64038935.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定