这是对此的后续问题。
我昨天问了这个问题,虽然它还没有解决,但我尝试对代码进行一些愚蠢的更改,使其只编译一次(用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.");
}
}
}
}