1

这是对此的后续问题。

我昨天问了这个问题,虽然它还没有解决,但我尝试对代码进行一些愚蠢的更改,使其只编译一次(用console.format()语句替换语句System.out.print,并null作为方法的第二个参数添加readLine())。

幸运的是,代码确实运行了,但它会打印出来No console.(显然是因为没有JVM控制台设备。 参考

那么如何获得应该由 Console 类的对象表示的控制台设备呢?


为方便起见,我在对代码进行了上述愚蠢的更改以使其运行后添加代码:-

import java.io.Console;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

/*
 *  Enter your regex: foo
 *  Enter input string to search: foo
 *  I found the text foo starting at index 0 and ending at index 3.
 * */

public class RegexTestHarness {

    public static void main(String[] args){
        Console console = System.console();
        if (console == null) {
            System.err.println("No console.");
            System.exit(1);
        }
        while (true) {

            Pattern pattern = 
            Pattern.compile(console.readLine("%nEnter your regex: ", null));

            Matcher matcher = 
            pattern.matcher(console.readLine("Enter input string to search: ", null));

            boolean found = false;
            while (matcher.find()) {
                /*console.format("I found the text" +
                    " \"%s\" starting at " +
                    "index %d and ending at index %d.%n",
                    matcher.group(),
                    matcher.start(),
                    matcher.end());*/

                System.out.println("I found the text " + matcher.group() + " starting at index " + matcher.start() + " and ending at index " + matcher.end() + "."); 

                found = true;
            }
            if(!found){
                //console.format("No match found.%n", null);
                System.out.println("No match found."); 
            }
        }
    }
}
4

1 回答 1

0

如果您的应用程序是从终端启动并且没有标准输入或标准输出重定向,那么您的应用程序将只有一个控制台设备可以打开。基本上,函数 isatty() 必须返回 true。如果 Windows 应用程序从资源管理器启动,它们通常没有控制台。您应该从命令提示符 (cmd.exe) 启动它们。

于 2014-06-16T03:50:20.247 回答