此代碼示出了一個方法來構建的格式字符串以及使用%8.3f
以顯示雙。
public static void main(String[] args)
{
String level = "Beginning";
String firstPlaceName = "TheWinner!";
double firstPlaceTime = 180.234534D;
double timeGain = 10.2D;
int numberOfRunners = 10;
StringBuilder sb = new StringBuilder();
sb.append("Level %-10s"); //the level
sb.append("|"); //divider
sb.append("%-18s"); //name of winner
sb.append("|"); //divider
sb.append("%8.3f s "); //winning time
sb.append("|"); //divider
sb.append("%8.3f s ahead"); //time gain
sb.append("|"); //divider
sb.append("%5d runners"); // # of runners
System.out.format(sb.toString(),
level,
firstPlaceName,
firstPlaceTime,
timeGain,
numberOfRunners);
}
輸出:
Level Beginning |TheWinner! | 180.235 s | 10.200 s ahead| 10 runners
編輯:闡述在評論的問題。 OP表示嘗試使用%8.3f
並收到格式錯誤。 firstPlaceTime
是一個雙。然而,被指定的參數爲:
...,firstPlaceTime + "s ",...
當+ "s "
被作爲參數提供,它會被轉換爲String
,然後傳遞到.format()
。作爲String
,它不會是通過%8.3f
規範格式化的double
。它是建議將文本移動到格式規範中的原因之一,而不是試圖在參數中嘗試各種字符串連接。
'firstPlaceTime'已經是一個字符串了嗎?在這種情況下,你需要先將其格式化,然後傳遞給'.format'。如果它是'double'(或'float'),那麼你可以使用'%8.3f'。除此之外:你爲什麼要將格式與String concatenation混合?只需將分隔線和文本放入格式本身即可。 – KevinO
@KevinO'firstPlaceTime'是一個double。我嘗試使用'%8.3f',它會拋出錯誤IllegalFormatConversion。我不熟悉將分隔符和文本添加到格式 –