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.
0
solved Inputing using Scanner class