I am learning regex,when I compile this code which is from Java Official documentation, I am getting No Console
error in this code,The source is, I am compiling this code in Eclipse, version Kepler.
The culprit is Console console = System.console();
but I do not know why the error is caused.
import java.io.Console;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
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: "));
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");
}
}
}
}
but I do not know why the error is caused
Presumably because you're not running it in a console. When you run a Java app in Eclipse, System.console()
returns null, because it's not a "normal" console. (Personally I think it would be better if Eclipse's console view could be used as the console for this purpose, but apparently that's not the case - at least not yet. See bug 122429.)
Open a console ("command prompt" in Windows parlance) and run the code there, and you should be fine.
Alternatively, change the code to use standard streams such as System.in
and System.out
to read input and write output, instead of using Console
.
See more on this question at Stackoverflow