以下代码是我从doc.oracle网站复制的完美代码。它在netbeans中编译没有任何错误,但输出是:
没有控制台。 Java结果:1
如何让控制台正常工作?是否需要在netbeans设置中进行任何调整?虽然我在IDE netbeans的java编程方面有一些经验,但我很困惑。我使用的是最新版本的JDK以及Netbean。
公共类RegexTestHarness {
/**
* @param args the command line arguments
*/
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: "));
Matcher matcher =
pattern.matcher(console.readLine("Enter input string to search: "));
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());
found = true;
}
if(!found){
console.format("No match found.%n");
}
}
}
}
答案 0 :(得分:4)
我正在使用最新版本的JDK以及Netbeans。
NetBeans使用自己的控制台,因此根本没有系统控制台。尝试在终端上运行它,它应该可以工作。
答案 1 :(得分:2)
来自the Javadoc:
如果此虚拟机具有控制台,则它由此类的唯一实例表示,可以通过调用
System.console()
方法获取该实例。如果没有可用的控制台设备,则调用该方法将返回null
。
NetBeans没有System.console()
。
使用System.in
阅读要写的System.out
。
答案 2 :(得分:1)
为后代
public class RegexTestHarness {
public static void main(String[] args) throws IOException{
while (true) {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("\nEnter your regex:");
Pattern pattern =
Pattern.compile(br.readLine());
System.out.println("\nEnter input string to search:");
Matcher matcher =
pattern.matcher(br.readLine());
boolean found = false;
while (matcher.find()) {
System.out.format("I found the text" +
" \"%s\" starting at " +
"index %d and ending at index %d.%n",
matcher.group(),
matcher.start(),
matcher.end());
found = true;
}
if(!found){
System.out.println("No match found.");
}
}
}
}