【发布时间】:2014-06-16 03:39:33
【问题描述】:
这是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.");
}
}
}
}
【问题讨论】:
-
如何运行这段代码?我感觉您正在使用 Eclipse、NetBeans 或 InteliiJ 等 IDE。
-
是的,我正在使用 Eclipse。
-
在这种情况下,this 你可能会感兴趣。
-
如果您对alternative options感兴趣
标签: java regex console console-application console.readline