0

这个问题在这里有一个后续问题。


遵循本教程并编译给定的 RegexTestHarness 分别在 console.readLine(String) 和 console.Format(String) 上给出以下错误:

  1. 类型 Console 中的方法 readLine() 不适用于参数 (String)

  2. 类型 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*****
            }
        }
    }
}

在此处输入图像描述

4

2 回答 2

3

来自JavaDoc 的Console

提供格式化提示,然后从控制台读取一行文本。

这是如何运作的?好吧,它使用带参数的格式字符串。参数是一个可变参数数组,因此您可以不传递任何参数或传递多个参数,而无需任何特殊语法。

例如

console.readLine("No arguments");

只会在提示符上输出“无参数”。

final String a = "A";
console.readLine("With string, %s", a);

将在提示符上输出“With string, A”。

final String a = "A";
final int b = 10;
console.readLine("With string %s and a formatted number %.2f", a, b);

将在提示符上输出“With string A and a formatted number 10.00”。

于 2014-06-15T08:55:19.367 回答
1

格式字符串(大部分)包含类似%d或的​​内容%s,这些项目应对应于方法调用中格式字符串之后的表达式:这些是“引用的参数”。

您在 Pattern/Matcher 调用中遇到了什么错误?

于 2014-06-15T08:52:44.023 回答