gpt4 book ai didi

java - 在记录的消息中逐字打印单引号参数

转载 作者:行者123 更新时间:2023-11-30 06:56:30 25 4
gpt4 key购买 nike

我正在尝试使用 java.util.logging.Logger.log(Level, String) 方法将一些参数打印到控制台中。但参数总是被逐字打印:

package loggertest;

import java.util.logging.Level;
import java.util.logging.Logger;

public class LoggerTest {
public static void main(String[] args) {
final Logger LOGGER = Logger.getLogger(LoggerTest.class.getName());

LOGGER.log(Level.INFO, "Some info: {0}.", "foo");
LOGGER.log(Level.INFO, "Some quoted info: '{0}'.", "foo");
}
}

当我在 Netbeans 中运行此命令时,输出为:

Jan 17, 2017 12:13:43 PM loggertest.LoggerTest main
INFO: Some info: foo.
Jan 17, 2017 12:13:43 PM loggertest.LoggerTest main
INFO: Some quoted info: {0}.

显然,当我们在单引号内使用参数(即 '{0}')时,它们会逐字打印。为什么会发生这种情况以及如何解决这个问题?

最佳答案

出现这个问题的原因是java.text.MessageFormatbeing used .

引用MessageFormat:

Within a String, a pair of single quotes can be used to quote any arbitrary characters except single quotes. For example, pattern string "'{0}'" represents string "{0}", not a FormatElement. A single quote itself must be represented by doubled single quotes '' throughout a String.

所以,解决方法是这样的:

LOGGER.log(Level.INFO, "Some correctly quoted info: ''{0}''.", "foo");

这将打印:

Jan 17, 2017 12:37:58 PM loggertest.LoggerTest main
INFO: Some correctly quoted info: 'foo'.

关于java - 在记录的消息中逐字打印单引号参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41690947/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com