What I understood from my past experiences is nextInt()
or nextDouble()
would keep on searching until the integer or the double is found in the same or the next line it doesn't matter,while to read a string as input through scanner class next()
considers those strings before space and keeps the cursor in the same line, where as nextLine()
would consider the leftovers by the next()
if used before the nextLine()
in code,could someone help me understand this in more detail,especially about nextLine()
where it starts and where the cursor ends? Also, please tell me if any mistakes I thought are correct.

- 2,393
- 1
- 19
- 50

- 3
- 3
-
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html – AJ. Nov 17 '16 at 10:21
1 Answers
Your first understanding is wrong.
what i understood from my past experiences is .nextInt() or .nextDouble() would keep on searching until the integer or the double is found in the same or the next line it doesn't matter
nextInt()
and nextDouble()
waits for the integer and double respectively. If it gets string instead of it's expectation, it throws InputMismatchException
.
You can run this code and see for yourself.
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
s.nextInt();
}
}
According to your quote:
.nextInt() or .nextDouble() would keep on searching until the integer or the double is found in the same or the next line it doesn't matter
Give input: Abcdf234gd
. You won't get 234
. You get InputMismatchException
.
For .next()
and .nextLine()
,
.next()
: Only reads and returns a string till it encounters a space or EOF
.
.nextLine()
: Returns string till it encounters \n
or \r
or EOF
. Means, it returns whole line.
Cursor Positions
next()
:
Consider the string:
ABC DEF GHI JKL MNO PQR STU VWX YZ
Initial Position:
->ABC DEF GHI JKL MNO PQR STU VWX YZ
When you call next()
, the cursor moves to:
ABC ->DEF GHI JKL MNO PQR STU VWX YZ
and returns ABC
nextLine()
:
Consider the string:
ABC DEF GHI JKL
MNO PQR STU VWX
YZ
Initial Position:
->ABC DEF GHI JKL
MNO PQR STU VWX
YZ
When you call nextLine()
, the cursor moves to next line:
ABC DEF GHI JKL
->MNO PQR STU VWX
YZ
and returns ABC DEF GHI JKL
.
I hope it helps.

- 2,393
- 1
- 19
- 50