console.readLine()和console.format():格式说明符引用的参数是什么意思?

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


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

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

  2. 参数类型Console中的方法格式(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: "));上收到错误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***** } } } } 

在此处输入图像描述

从JavaDoc for Console

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

这是如何运作的? 好吧,它使用带参数的格式字符串 。 参数是一个varargs数组,因此您可以在没有任何特殊语法的情况下传递none或many。

例如

 console.readLine("No arguments"); 

只会在提示符上输出“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); 

将“带字符串A和格式化的数字10.00”输出到提示符上。

格式字符串(主要)包含%d%s ,这些项应该对应于方法调用中格式字符串后面的表达式:这些是“引用的参数”。

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

Interesting Posts