【发布时间】:2020-03-30 08:47:00
【问题描述】:
我应该使用什么来代替 Scanner 以便 SonarQube 不会抱怨?
final Scanner scan = new Scanner(System.in);
【问题讨论】:
-
我认为 SQ 指的是“final”关键字。为什么 Scanner 是最终版?
我应该使用什么来代替 Scanner 以便 SonarQube 不会抱怨?
final Scanner scan = new Scanner(System.in);
【问题讨论】:
这是因为 SonarQube 中有以下 rule:
不应使用依赖于默认系统编码的类和方法
使用依赖于默认系统编码的类和方法可以使代码在其“家庭”环境中正常工作。但是,对于使用不同编码方式的客户,该代码可能会以极难诊断的方式出现故障,并且在修复它们时几乎(如果不是完全的话)不可能重现。
要修复它,您可以使用定义了编码类型的扫描仪:
/**
* Constructs a new <code>Scanner</code> that produces values scanned
* from the specified input stream. Bytes from the stream are converted
* into characters using the specified charset.
*
* @param source An input stream to be scanned
* @param charsetName The encoding type used to convert bytes from the
* stream into characters to be scanned
* @throws IllegalArgumentException if the specified character set
* does not exist
*/
public Scanner(InputStream source, String charsetName) {
this(makeReadable(Objects.requireNonNull(source, "source"), toCharset(charsetName)),
WHITESPACE_PATTERN);
}
【讨论】: