简体   繁体   中英

Java Scanner Input String

With a scanner, you use input.nextInt() for an int or input.nextDouble() for a double .

Why do you use input.nextLine() for a String instead of input.nextString() ?

The closest thing to nextString() is next() , which returns the next token , which by default is the next "word" (which is controlled by setting the delimiter, that defaults to whitespace).

nextLine() returns the (rest of the) current line (up to but not including the new line char(s)), regardless of the delimiter . That's why it's called line not String , because "line" most accurately describes what it does, rather than what type it returns which wouldn't distinguish itself from next()

Naming conventions make programs more understandable by making them easier to read. They can also give information about the function of the identifier-for example, whether it's a constant, package, or class-which can be helpful in understanding the code.

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. so:

Why would you call it nextString() if this method returns a line?

9 - Naming Conventions

Scanner class takes input and tries to convert it into mentioned datatype. If you have written nextDouble then it will try to convert data to Double datatype. If the conversion fails then it will throw an error.

In case of nextLine, it will take the complete next line and convert it to string because string can be n characters long. this is a test message is a string value.

String data can contain spaces whereas any other datatype won't.

For nextLine(), Scanner will match the string with LINE_PATTERN = ".*(\\r\\n|[\\n\\r ])|.+$" regex.

For nextDouble() or any other method you pass invalid input then it will throw an exception of java.util.InputMismatchException type.

To add up on other answers, all native types have fixed size in bytes (ie byte is 1, char and short is 2, long and double is 8, ...) so it is easy for Scanner to read just that amount of bytes and return the appropriate result.

Now, how many bytes is a String ? If it were C, it would be " until a nul character is found ", but nul characters are legal in Java strings so you can't know where to stop reading. That's why there is no nextString() method.

Instead, you could arbitrarily decide to end a string at a specific character, and that character ended up being the newline \\r\\n combination. The correct name for that method is then nextLine() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM