The Wayback Machine - https://web.archive.org/web/20240528010719/https://www.geeksforgeeks.org/scanner-nextint-method-in-java-with-examples/
Open In App

Scanner nextInt() method in Java with Examples

Last Updated : 12 Oct, 2018
Improve
Improve
Like Article
Like
Save
Share
Report

The nextInt(radix) method of java.util.Scanner class scans the next token of the input as a Int. If the translation is successful, the scanner advances past the input that matched. If the parameter radix is not passed, then it behaves similarly as nextInt(radix) where the radix is assumed to be the default radix.

Syntax:

public int nextInt()

Parameters: The function accepts a parameter radix which is used to interpret the token as a Int value.

Return Value: This function returns the Int scanned from the input.

Exceptions: The function throws three exceptions as described below:

  • InputMismatchException: if the next token does not matches the Integer regular expression, or is out of range
  • NoSuchElementException: throws if input is exhausted
  • IllegalStateException: throws if this scanner is closed

Below programs illustrate the above function:

Program 1:




// Java program to illustrate the
// nextInt() method of Scanner class in Java
// without parameter
  
import java.util.*;
  
public class GFG1 {
    public static void main(String[] argv)
        throws Exception
    {
  
        String s = "Gfg 9 + 6 = 12.0";
  
        // create a new scanner
        // with the specified String Object
        Scanner scanner = new Scanner(s);
  
        while (scanner.hasNext()) {
  
            // if the next is a Int,
            // print found and the Int
            if (scanner.hasNextInt()) {
                System.out.println("Found Int value :"
                                   + scanner.nextInt());
            }
  
            // if no Int is found,
            // print "Not Found:" and the token
            else {
                System.out.println("Not found Int value :"
                                   + scanner.next());
            }
        }
        scanner.close();
    }
}


Output:

Not found Int value :Gfg
Found Int value :9
Not found Int value :+
Found Int value :6
Not found Int value :=
Not found Int value :12.0

Program 2:




// Java program to illustrate the
// nextInt() method of Scanner class in Java
// with parameter
  
import java.util.*;
  
public class GFG1 {
    public static void main(String[] argv)
        throws Exception
    {
  
        String s = "Gfg 9 + 6 = 12.0";
  
        // create a new scanner
        // with the specified String Object
        Scanner scanner = new Scanner(s);
  
        while (scanner.hasNext()) {
  
            // if the next is a Int,
            // print found and the Int
            if (scanner.hasNextInt()) {
                System.out.println("Found Int value :"
                                   + scanner.nextInt(12));
            }
  
            // if no Int is found,
            // print "Not Found:" and the token
            else {
                System.out.println("Not found Int value :"
                                   + scanner.next());
            }
        }
        scanner.close();
    }
}


Output:

Not found Int value :Gfg
Found Int value :9
Not found Int value :+
Found Int value :6
Not found Int value :=
Not found Int value :12.0

Program 3: To demonstrate InputMismatchException




// Java program to illustrate the
// nextInt() method of Scanner class in Java
// InputMismatchException
  
import java.util.*;
  
public class GFG1 {
    public static void main(String[] argv)
        throws Exception
    {
  
        try {
  
            String s = "Gfg 9 + 6 = 12.0";
  
            // create a new scanner
            // with the specified String Object
            Scanner scanner = new Scanner(s);
  
            while (scanner.hasNext()) {
  
                // if the next is a Int,
                // print found and the Int
                // since the value 60 is out of range
                // it throws an exception
  
                System.out.println("Next Int value :"
                                   + scanner.nextInt());
            }
            scanner.close();
        }
        catch (Exception e) {
            System.out.println("Exception thrown: " + e);
        }
    }
}


Output:

Exception thrown: java.util.InputMismatchException

Program 4: To demonstrate NoSuchElementException




// Java program to illustrate the
// nextInt() method of Scanner class in Java
// NoSuchElementException
  
import java.util.*;
  
public class GFG1 {
    public static void main(String[] argv)
        throws Exception
    {
  
        try {
  
            String s = "Gfg";
  
            // create a new scanner
            // with the specified String Object
            Scanner scanner = new Scanner(s);
  
            // Trying to get the next Int value
            // more times than the scanner
            // Hence it will throw exception
            for (int i = 0; i < 5; i++) {
  
                // if the next is a Int,
                // print found and the Int
                if (scanner.hasNextInt()) {
                    System.out.println("Found Int value :"
                                       + scanner.nextInt());
                }
  
                // if no Int is found,
                // print "Not Found:" and the token
                else {
                    System.out.println("Not found Int value :"
                                       + scanner.next());
                }
            }
            scanner.close();
        }
        catch (Exception e) {
            System.out.println("Exception thrown: " + e);
        }
    }
}


Output:

Not found Int value :Gfg
Exception thrown: java.util.NoSuchElementException

Program 5: To demonstrate IllegalStateException




// Java program to illustrate the
// nextInt() method of Scanner class in Java
// IllegalStateException
  
import java.util.*;
  
public class GFG1 {
    public static void main(String[] argv)
        throws Exception
    {
  
        try {
  
            String s = "Gfg 9 + 6 = 12.0";
  
            // create a new scanner
            // with the specified String Object
            Scanner scanner = new Scanner(s);
  
            // close the scanner
            scanner.close();
            System.out.println("Scanner Closed");
  
            System.out.println("Trying to get "
                               + "next Int value");
  
            while (scanner.hasNext()) {
  
                // if the next is a Int,
                // print found and the Int
                if (scanner.hasNextInt()) {
                    System.out.println("Found Int value :"
                                       + scanner.nextInt());
                }
  
                // if no Int is found,
                // print "Not Found:" and the token
                else {
                    System.out.println("Not found Int value :"
                                       + scanner.next());
                }
            }
        }
        catch (Exception e) {
            System.out.println("Exception thrown: " + e);
        }
    }
}


Output:

Scanner Closed
Trying to get next Int value
Exception thrown: java.lang.IllegalStateException: Scanner closed

Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextInt(int)



Similar Reads

Java.util.Random.nextInt() in Java
Generating random numbers themselves have a good utility value and having them achieved by the usage of function can prove to be very useful. Java in its language has dedicated an entire library to Random numbers seeing its importance in day-day programming. nextInt() is discussed in this article. java.util.Random.nextInt() : The nextInt() is used
4 min read
Java Deprecated API Scanner tool (jdepscan) in Java 9 with Examples
Java Deprecated API Scanner tool: Java Deprecated API Scanner tool i.e. jdeprscan is a static analyzing command-line tool which is introduced in JDK 9 for find out the uses of deprecated API in the given input. Here the input can be .class file name, directory or JAR file. Whenever we provide any input to jdeprscan command line tool then it generat
2 min read
Scanner nextFloat() method in Java with Examples
The nextFloat() method of java.util.Scanner class scans the next token of the input as a Float(). If the translation is successful, the scanner advances past the input that matched. Syntax: public float nextFloat() Parameters: The function does not accepts any parameter. Return Value: This function returns the Float scanned from the input. Exceptio
4 min read
Scanner skip() method in Java with Examples
skip(Pattern pattern) The skip(Pattern pattern) method of java.util.Scanner class skips input that matches the specified pattern, ignoring the delimiters. The function skips the input if an anchored match of the specified pattern succeeds it. Syntax: public Scanner skip(Pattern pattern) Parameters: The function accepts a mandatory parameter pattern
5 min read
Scanner useRadix() method in Java with Examples
The useRadix(radix) method of java.util.Scanner class sets this scanner's default radix to the specified radix. A scanner's radix affects elements of its default number matching regular expressions. Syntax: public Scanner useRadix(int radix) Parameters: The function accepts a mandatory parameter radix which specifies the radix to use when scanning
2 min read
Scanner close() method in Java with Examples
The close() method ofjava.util.Scanner class closes the scanner which has been opened. If the scanner is already closed then on calling this method, it will have no effect. Syntax: public void close() Return Value: The function does not return any value. Below programs illustrate the above function: Program 1: // Java program to illustrate the // c
1 min read
Scanner delimiter() method in Java with Examples
The delimiter() method ofjava.util.Scanner class returns the Pattern this Scanner is currently using to match delimiters. Syntax: public Pattern delimiter() Return Value: The function returns the scanner's delimiting pattern. Below programs illustrate the above function: Program 1: // Java program to illustrate the // delimiter() method of Scanner
2 min read
Scanner findInLine() method in Java with Examples
findInLine(Pattern pattern) The findInLine(Pattern pattern) method of java.util.Scanner class tries to find the next occurrence of the specified pattern ignoring delimiters. If the pattern is found before the next line separator, the scanner advances past the input that matched and returns the string that matched the pattern. If no such pattern is
4 min read
Scanner useLocale() method in Java with Examples
The useLocale() method of java.util.Scanner class sets this scanner's locale to the specified locale. Syntax: public Scanner useLocale(Locale locale) Parameters: The function accepts a mandatory parameter locale which specifies a string specifying the locale to use. Return Value: The function returns this modified scanner. Exceptions: If the radix
2 min read
Scanner toString() method in Java with Examples
The toString() method of java.util.Scanner class returns the string representation of this Scanner. The exact format is unspecified. Syntax: public String toString() Return Value: This function returns the string representation of this scanner. Below program illustrates the above function: Program 1: // Java program to illustrate the // toString()
1 min read
Practice Tags :