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

我正在尝试使用.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。


忽然笑
浏览 1198回答 3
3回答

温温酱

虽然之前的所有回复都是正确的,但它们都是Java语言。这是一个Scala示例:val placeholder = "Hello %s, isn't %s cool?"val formatted = placeholder.format("Ivan", "Scala")我还有一篇关于制作format%可能有用的Python 操作符的博客文章。

萧十郎

您无需使用数字来指示定位。默认情况下,参数的位置只是它在字符串中出现的顺序。以下是使用此方法的正确方法示例: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所提到的,如果需要,您将在文档中看到可以更改默认参数排序。但是,您可能只需要/想要这样做的唯一时间就是您多次使用相同的参数。

POPMUISE

您应该阅读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
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java