本文翻譯自:How to use java.String.format in Scala?
I am trying to use a .format
method of a string. 我正在嘗試使用字符串的.format
方法。 But if I place %1, %2, etc. in the string, java.util.UnknownFormatConversionException is thrown pointing to a confusing Java source code piece: 但是如果我在字符串中放置%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));
}
}
From this I understand that %
char is forbidden. 據我所知, %
char是被禁止的。 If so, then what should I use for argument placeholders? 如果是這樣,那麼我應該將什麼用於參數佔位符?
I use Scala 2.8. 我使用Scala 2.8。
#1樓
參考:https://stackoom.com/question/FVIU/如何在Scala中使用java-String-format
#2樓
Here is a list of formatters used with String.format() 以下是與String.format()一起使用的格式化程序列表
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html
#3樓
官方參考是Formatter
類。
#4樓
In Scala 2.10 在Scala 2.10中
val name = "Ivan"
val weather = "sunny"
s"Hello $name, it's $weather today!"
#5樓
You can use this; 你可以用這個;
String.format("%1$s %2$s %2$s %3$s", "a", "b", "c");
Output: 輸出:
abbc ABBC
#6樓
This is a list of what String.format
can do. 這是String.format
可以執行的操作的列表。 The same goes for printf
printf
int i = 123;
o.printf( "|%d|%d|%n" , i, -i ); // |123|-123|
o.printf( "|%5d|%5d|%n" , i, -i ); // | 123| –123|
o.printf( "|%-5d|%-5d|%n" , i, -i ); // |123 |-123 |
o.printf( "|%+-5d|%+-5d|%n" , i, -i ); // |+123 |-123 |
o.printf( "|%05d|%05d|%n%n", i, -i ); // |00123|-0123|
o.printf( "|%X|%x|%n", 0xabc, 0xabc ); // |ABC|abc|
o.printf( "|%04x|%#x|%n%n", 0xabc, 0xabc ); // |0abc|0xabc|
double d = 12345.678;
o.printf( "|%f|%f|%n" , d, -d ); // |12345,678000| |-12345,678000|
o.printf( "|%+f|%+f|%n" , d, -d ); // |+12345,678000| |-12345,678000|
o.printf( "|% f|% f|%n" , d, -d ); // | 12345,678000| |-12345,678000|
o.printf( "|%.2f|%.2f|%n" , d, -d ); // |12345,68| |-12345,68|
o.printf( "|%,.2f|%,.2f|%n" , d, -d ); // |12.345,68| |-12.345,68|
o.printf( "|%.2f|%(.2f|%n", d, -d ); // |12345,68| |(12345,68)|
o.printf( "|%10.2f|%10.2f|%n" , d, -d ); // | 12345,68| | –12345,68|
o.printf( "|%010.2f|%010.2f|%n",d, -d ); // |0012345,68| |-012345,68|
String s = "Monsterbacke";
o.printf( "%n|%s|%n", s ); // |Monsterbacke|
o.printf( "|%S|%n", s ); // |MONSTERBACKE|
o.printf( "|%20s|%n", s ); // | Monsterbacke|
o.printf( "|%-20s|%n", s ); // |Monsterbacke |
o.printf( "|%7s|%n", s ); // |Monsterbacke|
o.printf( "|%.7s|%n", s ); // |Monster|
o.printf( "|%20.7s|%n", s ); // | Monster|
Date t = new Date();
o.printf( "%tT%n", t ); // 11:01:39
o.printf( "%tD%n", t ); // 04/18/08
o.printf( "%1$te. %1$tb%n", t ); // 18. Apr