我對printf非常不滿。如何添加%$ 2F到我的字符串格式,這樣我可以得到的東西乾淨這樣的: (我忘了添加「$」更早)java:我如何使用printf打印美元符號和帶2位小數的雙精度值?
MP3 Player cost: $580.39
Smart Phone cost: $510.93
Digital Watch cost: $495.99
Tablet cost: $643.17
Portable Gaming System cost: $485.17
import java.util.Scanner;
public class test2 {
public static void main(String[] arg) {
Scanner in = new Scanner(System.in);
int [][] matrix = { // 5 rows, 7 cols
{ 9, 13, 4, 7, 1, 14, 10},
{ 8, 2, 12, 11, 6, 15, 2},
{ 9, 6, 7, 10, 15, 8, 3},
{ 12, 14, 8, 15 ,2 , 7, 8},
{ 12, 10, 3, 11, 8, 3, 5},
};
String [] product = new String [5];
product [0] = "MP3 Player";
product [1] = "Smart Phone";
product [2] = "Digital Watch";
product [3] = "Tablet";
product [4] ="Portable Gaming System";
double [] price = {10.75, 15.27, 5.98, 9.67, 4.32, 12.50, 1.42}; // 7 elements
costOfEach(matrix, product, price);
}
// compute and display the cost of manufacturing each device
public static double costOfEach(int matrix[][], String[] product, double price []){
double cost = 0.00;
String item = "";
double maxCost = 0.00;
double minCost = Double.MAX_VALUE;
int maxCostIndex = 0;
int minCostIndex = 0;
這項權利在這裏。我嘗試了很多組合但沒有結果
String format = "%-40s%s%n";
for (int row = 0; row < matrix.length; row++){
cost = 0;
for (int col = 0, i = 0; col < matrix[0].length && i < price.length; col++, i++){
cost += matrix[row][col] * price [i];
}
System.out.printf(format, product[row] + " cost: $%.2f", cost);
}
return cost;
}
}
[printf cheatsheet](http://alvinalexander.com/programming/printf-format-cheat-sheet) – rafid059
謝謝你的回覆。你能否告訴我們更多關於如何將這些格式組合在一起的信息?它會更有幫助。 – Neo