Scanner hasNextBigInteger(int) in Java

hasNextBigInteger(int): This method is available in java.util.Scanner class of Java.

Syntax:

boolean java.util.Scanner.hasNextBigInteger(int radix)

This method takes one argument. This method returns true if the next token in this scanner's input can be interpreted as a BigInteger in the specified radix

Parameters: One parameter is required for this method.

radix: the radix used to interpret the token as an integer.

Returns: true if and only if this scanner's next token is a valid BigInteger.

Throws:

1. IllegalStateException - if this scanner is closed.

2. IllegalArgumentException - if the radix is out of range

Approach 1: When no exception

Java

import java.util.Scanner;

public class ScannerhasNextBigInteger2 {
    public static void main(String[] args) {

        String source = "Hello World";
        Scanner scanner = new Scanner(source);

        int radix = Character.MIN_RADIX;
        System.out.println(scanner.hasNextBigInteger(radix));

        scanner.close();
    }
}

Output:

false


Approach 2: IllegalStateException 

Java

import java.util.Scanner;

public class ScannerhasNextBigInteger2 {
    public static void main(String[] args) {

        String source = "Hello World";
        Scanner scanner = new Scanner(source);

        int radix = Character.MIN_RADIX;
        scanner.close();
        System.out.println(scanner.hasNextBigInteger(radix));

    }
}

Output:

Exception in thread "main" java.lang.IllegalStateException: Scanner closed at java.base/java.util.Scanner.ensureOpen(Scanner.java:1150) at java.base/java.util.Scanner.hasNext(Scanner.java:1540) at java.base/java.util.Scanner.hasNextBigInteger(Scanner.java:2605)



Approach 3: IllegalArgumentException 

Java

import java.util.Scanner;

public class ScannerhasNextBigInteger2 {
    public static void main(String[] args) {

        String source = "Hello World";
        Scanner scanner = new Scanner(source);

        int radix = Character.MIN_RADIX - 1;
        System.out.println(scanner.hasNextBigInteger(radix));

        scanner.close();
    }
}

Output:

Exception in thread "main" java.lang.IllegalArgumentException: radix:1 at java.base/java.util.Scanner.setRadix(Scanner.java:1368) at java.base/java.util.Scanner.hasNextBigInteger(Scanner.java:2604)



No comments:

Post a Comment