Java 为什么是 nextLine() 而不是 nextString() ?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41965972/
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-08-11 23:49:36  来源:igfitidea点击:

Why nextLine() and not nextString() ?

javamethods

提问by user5482698

I'm new to Java and I just started learning this language.

我是 Java 新手,刚开始学习这门语言。

There is one thing I don't get. I have to use nextInt()to get an Int from the user. But when I need to get a string I have to write nextLine().

有一件事我不明白。我必须使用nextInt()从用户那里获取 Int 。但是当我需要得到一个字符串时,我必须写nextLine().

Why is that?

这是为什么?

P.S: That can sound like a stupid question but I need to know :-)

PS:这听起来像是一个愚蠢的问题,但我需要知道:-)

回答by yalpsid eman

They are specific functions and are expecting specific user inputs. That is the way they were made.

它们是特定的功能,需要特定的用户输入。这就是它们的制作方式。

I'd check out http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.htmlto get information about them.

我会查看http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html以获取有关它们的信息。

Specifically, look at http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine()http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextInt()

具体看http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine() http://docs.oracle.com/javase/7/docs/api /java/util/Scanner.html#nextInt()

回答by Andrii Plotnikov

Consider this: nextLine return everything until next endline (\n) in form of String. Would you not think that you will retrieve everything if it was called nextString? In that case you would be posting question "why nextString() stops at endline"

考虑一下:nextLine 以字符串的形式返回直到下一个结束行 (\n) 的所有内容。如果它被称为 nextString,你不会认为你会检索所有内容吗?在这种情况下,您将发布问题“为什么 nextString() 停在结束线”

tl;dr it's because it searches for endline (\n)

tl;dr 这是因为它搜索结束线 (\n)

upd: on documenatation it refers to it as "skipped" part. I.e. cursor goes to next line and returns everything "skipped". Default output is String, so you have it: everything skipped as String.

upd:在文档中,它将其称为“跳过”部分。即光标转到下一行并返回“跳过”的所有内容。默认输出是字符串,因此您拥有它:所有内容都作为字符串跳过。