Minerva
Minerva

Reputation: 157

Why nextLine() and not nextString() ?

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

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().

Why is that?

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

Upvotes: 3

Views: 54379

Answers (2)

Andrii Plotnikov
Andrii Plotnikov

Reputation: 3372

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"

tl;dr it's because it searches for endline (\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.

Upvotes: 4

yalpsid eman
yalpsid eman

Reputation: 3432

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.html to get information about them.

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()

Upvotes: 1

Related Questions