This question has a follow-up question here.
Following this tutorial and compiling the given RegexTestHarness is giving the following errors on console.readLine(String) and console.Format(String), respectively:
The method readLine() in the type Console is not applicable for the arguments (String)
The method format(String, Object[]) in the type Console is not applicable for the arguments (String, String, int, int)
According to the documentation, there are two arguments required there:
public String readLine(String fmt, Object... args
)public Console format(String fmt, Object... args
)
The second argument of type Object for both the methods is:
- args - Arguments referenced by the format specifiers in the format string. If there are more arguments than format specifiers, the extra arguments are ignored. The number of arguments is variable and may be zero. The maximum number of arguments is limited by the maximum dimension of a Java array as defined by.
So I believe that it changed after the tutorial was published.
QUESTION:-
What is meant the arguments referenced by the format specifiers?
Firstly I thought that it is the format specifiers themselves but then I am also getting an error on Matcher matcher = pattern.matcher(console.readLine("Enter input string to search: "));
statement.
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: ")); //********ERROR*****
Matcher matcher =
pattern.matcher(console.readLine("Enter input string to search: ")); //********ERROR*****
boolean found = false;
while (matcher.find()) {
console.format("I found the text" + //********ERROR*****
" \"%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"); //********ERROR*****
}
}
}
}
A format string (mostly) contains things like
%d
or%s
and these items should correspond to expressions following the format string in the method call: these are the "referenced arguments".What error did you get for the Pattern/Matcher call?
From the JavaDoc for
Console
:How does this work? Well, it uses a format string with parameters. The parameters are a varargs array so you can pass none or many without any special syntax.
For example
Will just output "No arguments" onto the prompt.
Will output "With string, A" onto the prompt.
Will output "With string A and a formatted number 10.00" onto the prompt.