0

This confusion is from I using the java Scanner nextLine method. If I firstly use the nextInt method and read a number, and then when I use the nextLine method, I must invoke it to skip the current line. I can understand this things in .txt file, things should like this: after I read a number, and I type a ENTER, now the cursor is in next line, and when I invoke the nextLine method, it will return the empty current line first.

But what does the ENTER(newline character) mean to computer(not the .txt file), and what will the computer do when I type a Enter key, it read a char such as '\n', or do something else.

If it is difficult to described, Can you suggest some relative books.

Micarle
  • 131
  • 9
  • "But what if in an IO model, or the memory model, what does the ENTER(newline character) mean to computer, and what will happen when we type an ENTER." - That sentence is quite confusing. – Thomas Oct 06 '16 at 09:02
  • Sorry about that, and I change that sentence. – Micarle Oct 06 '16 at 09:13

1 Answers1

1

The newline character(s) serve to signal the end of line in a character sequence. For the console the ENTER key serves to transmit the line buffer to the software: before that you may still delete characters and correct the line. The enter key results in a newline character in the transmitted line.

A "line" has nothing special for the general I/O but already you saw:

  • buffered input may flush the buffered text to the real output on line break.
  • Scanner needs a full line to recognize a number, because it has to read the first non-digit to have the full number recognized.

The most used line endings are:

  • \n on Linux, Android, MacOSX: LF = LINEFEED
  • \r\n on Windows: CR = CARRIAGE RETURN + LF
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
  • `nextLine` delivers the (remaining) line without line endings, that it reads too. If the line contains just one int, the read position is at the end, but will not skip the newline, unless nextLine is called. The class `Scanner` is so error prone, I find it an API to avoid when possible. Also the alternative BufferedReader has a readLine that return a line without line endings. Dropping the line endings is fine; now Windows and Linux can be treated the same. – Joop Eggen Oct 06 '16 at 09:36
  • You mean that the empty line returned when I invoke the nextLine after the invoking of nextInt is not generated by the ENTER. It is because that after the nextInt invoking, the read position is at the end of current line, and of course it is empty. Right? – Micarle Oct 06 '16 at 09:46
  • Yes, actually consuming the line break. – Joop Eggen Oct 06 '16 at 09:51
  • The ENTER just transmit the line buffer to the software and tell the software this is one line. – Micarle Oct 06 '16 at 09:52