Scanner forEachRemaining(Consumer) in Java

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

Syntax:

void java.util.Iterator.forEachRemaining(Consumer<? super String> action)

This method takes one argument. This method performs the given action for each remaining element until all elements have been processed or the action throws an exception.

Parameters: One parameter is required for this method.

action: The action to be performed for each element.

Throws:

NullPointerException - if the specified action is null.

Approach 1: When no exception

Java

import java.util.Scanner;

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

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

        scanner.forEachRemaining((n ->
System.out.print(n + " ")));
        scanner.close();
    }
}

Output:

Hello World 


Approach 2: NullPointerException

Java

import java.util.Scanner;

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

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

        scanner.forEachRemaining(null);
        scanner.close();
    }
}

Output:

Exception in thread "main" java.lang.NullPointerException at java.base/java.util.Objects.requireNonNull(Objects.java:208) at java.base/java.util.Iterator.forEachRemaining(Iterator.java:131)


No comments:

Post a Comment