KnowledgeBoat Logo

Computer Science

What is a token? Explain these methods while reading token from Scanner object.

(a) nextlnt( )      (b) nextDouble( )
(c) next( )           (d) nextLine( )

Values & Data Types Java

1 Like

Answer

Token is a set of characters separated by simultaneous blank spaces or delimiters. The different methods to read tokens from Scanner object are:

nextInt()

It reads the next token from Scanner object which can be expressed as an integer and stores in integer type variable. Its syntax is:

int <variable> = <ScannerObject>.nextInt();

Example

Scanner in = new Scanner(System.in);
int p;
p = in.nextInt();

nextDouble()

It reads the next token from Scanner object which can be expressed as a double type value and stores it in double type variable. Its syntax is:

double <variable> = <ScannerObject>.nextDouble();

Example

Scanner in = new Scanner(System.in);
double d;
d = in.nextDouble();

next()

It reads the next complete token from Scanner object and returns it as a String. A complete token is preceded and followed by input that matches the delimiter pattern set by useDelimiter method. If no pattern is explicitly set, space is used as the default delimiter to separate tokens. Its syntax is:

String \<variable> = \<ScannerObject>.next();

Example

Scanner in = new Scanner(System.in);
String str;
str = in.next();

nextLine()

It reads a complete line from Scanner object and returns it as a String. Its syntax is:

String \<variable> = \<ScannerObject>.nextLine();

Example

Scanner in = new Scanner(System.in);
String str;
str = in.nextLine();

Answered By

3 Likes


Related Questions