Search code examples
java.util.scannerautocloseable

auto closable not working with Scanner


package org.test;

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class RegTest {
    public static void main(String[] args) throws InterruptedException {
        String str = readLine("Enter String :");
        String patternString = readLine("Enter pattern to search :");

        Pattern pattern = Pattern.compile(patternString);
        Matcher matcher = pattern.matcher(str);

        System.out.print("match positions: "); // matches positions
        while(matcher.find()) {
            System.out.print(matcher.start() + " ");
        }
        System.out.println("");
    }


    static String readLine(String message){
        String strLine;
            try (Scanner in = new Scanner(System.in)) {
                System.out.println(message);
                strLine= in.nextLine();
            }
        return strLine;
    }
}

Did not work.

Output is :

Enter String :
wewew
Enter pattern to search :
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1585)
at org.test.RegTest.readLine(RegTest.java:39)
at org.test.RegTest.main(RegTest.java:22)


Solution

  • When the try-with-resources (autoclosable) closes the scanner it also closes the inputstream making it unavailable for use in the future.

    As System.in is a global inputstream it means the second scanner can't read any thing from the inputstream because it has been closed and it throws the exception.

    I would change the code to reuse the sanner for both reads.

    public static void main(String[] args) throws InterruptedException {
        try (Scanner in = new Scanner(System.in)) {
            String str = readLine(in, "Enter String :");
            String patternString = readLine(in, "Enter pattern to search :");
    
            Pattern pattern = Pattern.compile(patternString);
            Matcher matcher = pattern.matcher(str);
    
            System.out.print("match positions: "); // matches positions
            while (matcher.find()) {
                System.out.print(matcher.start() + " ");
            }
            System.out.println("");
        }
    
    }
    
    static String readLine(Scanner in, String message) {
        String strLine;
        System.out.println(message);
        strLine = in.nextLine();
        return strLine;
    }