Java Scanner - nextInt() Method
The java.util.Scanner.nextInt() method is used to scan the next token of the input as an int. An invocation of this method of the form nextInt() behaves in exactly the same way as the invocation nextInt(radix), where radix is the default radix of this scanner.
Syntax
public int nextInt()
Parameters
No parameter is required.
Return Value
Returns the int scanned from the input.
Exception
- Throws InputMismatchException, if the next token does not match the Float regular expression, or is out of range.
- Throws NoSuchElementException, if input is exhausted.
- Throws IllegalStateException, if this scanner is closed.
Example:
In the example below, the java.util.Scanner.nextInt() method is used to scan the next token of the input as an int.
import java.util.*; public class MyClass { public static void main(String[] args) { //String to scan String MyString = "Hello World 10 + 20 = 30.0"; //creating a Scanner Scanner MyScan = new Scanner(MyString); while(MyScan.hasNext()) { //if the next is an int if(MyScan.hasNextInt()) System.out.println("Int value is: "+ MyScan.nextInt()); //if the next is not an int else System.out.println("No Int Value found: "+ MyScan.next()); } //close the scanner MyScan.close(); } }
The output of the above code will be:
No Int Value found: Hello No Int Value found: World Int value is: 10 No Int Value found: + Int value is: 20 No Int Value found: = No Int Value found: 30.0
❮ Java.util - Scanner