java.util.Scanner next()
Description :
This java tutorial shows how to use the next() method of Scanner class of java.util package. This method returns a String object which is a complete token of the Scanner object.
Method Syntax :
public String next()
Parameter Input :
DataType | Parameter | Description |
---|---|---|
N/A | N/A | N/A |
Method Returns :
This method simply returns the next token of the Scanner object.
Compatibility Version :
Requires Java 1.5 and up
Exception :
NoSuchElementException
– The NoSuchElementException is thrown if and only if there is no available token
IllegalStateException
– This exception is thrown if the scanner is already closed before invoking the next() method.
Discussion :
The method next() gets the next token on the Scanner buffer matching the pattern used as delimiter on the scanner object. This method is used to iterate through the Scanner tokens while returning the value of the current token.
Java Code Example :
This java example source code demonstrates the use of next() method of Scanner class. Basically this code reads a full name from the input console and we have used the scanner object to store the information. We then tokenize the String input and then get the String tokens by invoking the next() method of this Scanner object.
package com.javatutorialhq.java.tutorial.scanner; import java.util.Scanner; /* * This is an example source code that reads input from console * and tokenize using Scanner object * Prints the tokens using next() method */ public class ScannerNextDemo { public static void main(String[] args) { System.out.print("Enter your full name:"); // Initialize Scanner object // read the value from the console Scanner scan = new Scanner(System.in); // read the first token String firstName = scan.next(); // read the second token String lastName = scan.next(); // Printing the token values of read by Scanner object System.out.println("First Name is "+firstName); System.out.println("Last Name is "+lastName); // closing the scanner stream scan.close(); } }
Sample Output :
Running the next() method example source code of Scanner class will give you the following output
Exception Scenario :
Exception in thread "main" java.lang.IllegalStateException: Scanner closed at java.util.Scanner.ensureOpen(Unknown Source) at java.util.Scanner.next(Unknown Source) at com.teknoscope.java.tutorial.scanner.ScannerNextDemo.main(ScannerNextDemo.java:29) Exception in thread "main" java.util.NoSuchElementException at java.util.Scanner.throwFor(Unknown Source) at java.util.Scanner.next(Unknown Source) at com.teknoscope.java.tutorial.scanner.ScannerHasNextDemo.main(ScannerHasNextDemo.java:22)
Similar Method :
- N/A
Suggested Reading List :
References :