Scanner next() in Java

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

Syntax:

String java.util.Scanner.next()

This method finds and returns the next complete token from this scanner.

Parameters: NA

Returns: the next token.

Throws:

1. NoSuchElementException - if no more tokens are available.

2. IllegalStateException - if this scanner is closed.

Approach 1: When no exception

Java

import java.util.Scanner;

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

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

        System.out.println(scanner.next());

        scanner.close();
    }
}

Output:

Hello


Approach 2: NoSuchElementException 

Java

import java.util.Scanner;

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

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

        System.out.println(scanner.next());

        scanner.close();
    }
}

Output:

Exception in thread "main" java.util.NoSuchElementException at java.base/java.util.Scanner.throwFor(Scanner.java:937) at java.base/java.util.Scanner.next(Scanner.java:1478)



Approach 3: IllegalStateException 

Java

import java.util.Scanner;

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

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

        scanner.close();
        System.out.println(scanner.next());

    }
}

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.next(Scanner.java:1465)


No comments:

Post a Comment