自动关闭不能使用扫描仪

时间:2015-08-14 21:59:45

标签: java.util.scanner autocloseable

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;
    }
}

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; } }

没用。

输出是:

输入字符串:
wewew
输入要搜索的模式:
线程“main”java.util.NoSuchElementException中的异常:找不到行     在java.util.Scanner.nextLine(Scanner.java:1585)
    在org.test.RegTest.readLine(RegTest.java:39)
    在org.test.RegTest.main(RegTest.java:22)

1 个答案:

答案 0 :(得分:1)

当try-with-resources(autoclosable)关闭扫描程序时,它还会关闭输入流,使其在将来无法使用。

由于System.in是一个全局输入流,这意味着第二个扫描程序无法读取输入流中的任何内容,因为它已被关闭并且会抛出异常。

我会更改代码以重复使用sanner进行两次读取。

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;
}