Leo Jiang
Leo Jiang

Reputation: 26213

Java Scanner without advancing to the next line?

I'm using Scanner.nextLine() to get input. Is there a way to not go to the next line when the enter key is pressed?

Sample code:

Scanner sc=new Scanner(System.in);
while (true) {
    input=sc.nextLine();
    ...
}

When the user presses enter, the current line is captured by the scanner and further input is on the next line. Is there a way for the user to press enter to send the input, but still stay on the same line for the next piece of input?

Upvotes: 1

Views: 8667

Answers (2)

dm78
dm78

Reputation: 1620

If your question is essentially "can I read an enter keypress using Scanner without moving the cursor on-screen?" then I believe the answer is no. Java's Scanner isn't really setup to function that way. You may be able to find a library that will allow you to accomplish this. Unfortunately I don't know of one. :/

Upvotes: 1

MarsAtomic
MarsAtomic

Reputation: 10696

You can use next(), but be advised that next() operates on tokens. The method will return anything in your line up to the first space that it encounters.

Upvotes: 1

Related Questions