这是 this 的后续问题。
我昨天问了这个问题,虽然还没有解决,但我尝试对代码进行一些愚蠢的更改,使其编译一次(将 console.format()
语句替换为 System.out.print
语句,并将 null
添加为 readLine()
方法的第二个参数)。
幸运的是,代码确实运行了,但它打印出No console.
(显然是因为JVM
没有控制台设备。 Reference)
那么如何获取控制台设备,应该由 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.");
}
}
}
}
最佳答案
如果您的应用程序是从终端启动并且没有 stdin 或 stdout 重定向,则它只会打开一个控制台设备。 基本上函数 isatty() 必须返回 true。如果 Windows 应用程序从资源管理器启动,则通常没有控制台。您应该从命令提示符 (cmd.exe) 启动它们。
关于java - 未找到控制台。如何获取 JVM 的控制台?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24236355/