为了账号安全,请及时绑定邮箱和手机立即绑定

如何在Scala中使用java.String.format?

如何在Scala中使用java.String.format?

忽然笑 2019-08-30 15:47:52
我正在尝试使用.format字符串的方法。但是如果我在字符串中放置%1,%2等,则会抛出java.util.UnknownFormatConversionException指向令人困惑的Java源代码段:private void checkText(String s) {    int idx;    // If there are any '%' in the given string, we got a bad format    // specifier.    if ((idx = s.indexOf('%')) != -1) {        char c = (idx > s.length() - 2 ? '%' : s.charAt(idx + 1));        throw new UnknownFormatConversionException(String.valueOf(c));    }}据此我明白,%禁止使用char。如果是这样,那么我应该将什么用于参数占位符?我使用Scala 2.8。
查看完整描述

3 回答

?
温温酱

TA贡献1752条经验 获得超4个赞

虽然之前的所有回复都是正确的,但它们都是Java语言。这是一个Scala示例:


val placeholder = "Hello %s, isn't %s cool?"

val formatted = placeholder.format("Ivan", "Scala")

我还有一篇关于制作format%可能有用的Python 操作符的博客文章。


查看完整回答
反对 回复 2019-08-30
?
萧十郎

TA贡献1815条经验 获得超13个赞

您无需使用数字来指示定位。默认情况下,参数的位置只是它在字符串中出现的顺序。


以下是使用此方法的正确方法示例:


String result = String.format("The format method is %s!", "great");

// result now equals  "The format method is great!".

您将始终使用a %后跟其他一些字符让方法知道它应该如何显示字符串。  %s可能是最常见的,它只是意味着参数应该被视为一个字符串。


我不会列出所有选项,但我会举几个例子来给你一个想法:


// we can specify the # of decimals we want to show for a floating point:

String result = String.format("10 / 3 = %.2f", 10.0 / 3.0);

// result now equals  "10 / 3 = 3.33"


// we can add commas to long numbers:

result = String.format("Today we processed %,d transactions.", 1000000);

// result now equals  "Today we processed 1,000,000 transactions."

String.format只使用a java.util.Formatter,所以有关选项的完整描述,您可以看到Formatter javadocs。


并且,正如BalusC所提到的,如果需要,您将在文档中看到可以更改默认参数排序。但是,您可能只需要/想要这样做的唯一时间就是您多次使用相同的参数。


查看完整回答
反对 回复 2019-08-30
?
POPMUISE

TA贡献1765条经验 获得超5个赞

您应该阅读javadoc String.format()和Formatter语法,而不是查看源代码。


您可以在%之后指定值的格式。例如,对于十进制整数,它是d,对于String,它是s:


String aString = "world";

int aInt = 20;

String.format("Hello, %s on line %d",  aString, aInt );

输出:


Hello, world on line 20

要执行您尝试的操作(使用参数索引),您使用:*n*$,


String.format("Line:%2$d. Value:%1$s. Result: Hello %1$s at line %2$d", aString, aInt );

输出:


Line:20. Value:world. Result: Hello world at line 20


查看完整回答
反对 回复 2019-08-30
  • 3 回答
  • 0 关注
  • 1197 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号