这个问题在这里有一个后续问题。
遵循本教程并编译给定的 RegexTestHarness 分别在 console.readLine(String) 和 console.Format(String) 上给出以下错误:
类型 Console 中的方法 readLine() 不适用于参数 (String)
类型 Console 中的方法 format(String, Object[]) 不适用于参数 (String, String, int, int)
根据文档,那里需要两个参数:
public String readLine(String fmt, Object... args
)public Console format(String fmt, Object... args
)
两种方法的 Object 类型的第二个参数是:
- args - 格式字符串中的格式说明符引用的参数。如果参数多于格式说明符,则忽略多余的参数。参数的数量是可变的,可能为零。参数的最大数量受定义的 Java 数组的最大维度限制。
所以我相信它在教程发布后发生了变化。
问题:-
格式说明符引用的参数是什么意思?
首先,我认为这是格式说明符本身,但随后我在 Matcher matcher = pattern.matcher(console.readLine("Enter input string to search: "));
声明中也遇到了错误。
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*****
}
}
}
}