Java:.nextLine() 和 .nextDouble() 区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11551985/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 05:31:55  来源:igfitidea点击:

Java: .nextLine() and .nextDouble() differences

javamethods

提问by Ryan Christman

I was reading the API for Java because I had a question on the difference between .nextLine()and .nextDouble(). In the API, it says this for .nextLine():

我读了API的Java,因为我对之间的差异问题.nextLine().nextDouble()。在 API 中,它说.nextLine()

"Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line."

“将此扫描器推进到当前行并返回被跳过的输入。此方法返回当前行的其余部分,不包括末尾的任何行分隔符。位置设置为下一行的开头。”

Easy enough...it skips the current line you are on and then returns the line you just skipped. But for .nextDouble(), it says this:

很简单……它跳过您所在的当前行,然后返回您刚刚跳过的行。但是对于.nextDouble(),它是这样说的:

"Scans the next token of the input as a double. This method will throw InputMismatchException if the next token cannot be translated into a valid double value. If the translation is successful, the scanner advances past the input that matched."

“将输入的下一个标记扫描为双精度值。如果下一个标记无法转换为有效的双精度值,则此方法将抛出 InputMismatchException。如果转换成功,扫描仪将通过匹配的输入。”

So does this mean that .nextDouble()does not skip to a new line and that it only reads until the end of the double and then stops at the end of the line? This would help me in understanding a program I'm working on now. Thanks guys and gals!

那么这是否意味着.nextDouble()它不会跳到新行,而是只读取到双精度值的末尾,然后在行尾停止?这将帮助我理解我现在正在处理的程序。谢谢你们!

采纳答案by tommo

nextDouble()

only reads the next 4 bytes from the input stream which make up the double and does not advance to the next line, whereas nextLine() does. Also i think you need to understand that a new line is designated by the string '\n', and obviously a number will not contain a linebreak, so 'nextDouble()' will not 'advance' to the next line.

只从构成双精度的输入流中读取接下来的 4 个字节,并且不会前进到下一行,而 nextLine() 会。此外,我认为您需要了解一个新行是由字符串 '\n' 指定的,显然一个数字不会包含换行符,因此 'nextDouble()' 不会'前进'到下一行。

EDIT: Razvan is right

编辑:拉兹万是对的

回答by Razvan

It reads the next token (between 2 separating characters,white characters usually), not the next 4 bytes. It then transforms that token to a double if it can.

它读取下一个标记(在 2 个分隔字符之间,通常是白色字符),而不是接下来的 4 个字节。如果可以,它然后将该令牌转换为双精度值。

Ex: Bla bla bla 12231231.2121 bla bla.

The 4th token can be read using nextDouble(). It reads 13 chars and it transforms that string into a double if possible.

可以使用 nextDouble() 读取第 4 个标记。它读取 13 个字符,并在可能的情况下将该字符串转换为双精度。