2014-01-25 51 views
0

我想使用一些新的Java字符串格式化技巧,很基本的東西。它編譯沒有任何錯誤消息,但不會允許我執行代碼。有人可以向我解釋爲什麼這是錯的嗎?提前致謝。字符串格式不工作

我的代碼:

class TestingStringFormat { 
    public static void main(String args[]) { 
     System.out.printf("Total cost %-10d ; quantity %d\n", "ten spaces",5, 120); 

     for(int i=0; i<20; i++){ 
     System.out.printf("%-2d: ", i, "some text here/n", 1); 
    } 
    } 
} 

回答

2

在這兩個你printf S的,格式說明符的數量不符的要傳遞的參數個數

例如,第一printf讀取:

System.out.printf("Total cost %-10d ; quantity %d\n", "ten spaces",5, 120); 

它期待一個整數後跟另一個整數。您正在傳遞Stringint和另一個int

在你的第二個printf

System.out.printf("%-2d: ", i, "some text here/n", 1); 

該公司預計一個整數。您正在通過intString和另一個int

1

你錯過了對應於第一String參數上printf方法,這樣一IllegalFormatConversionException將拋出的格式說明

System.out.printf("Total cost %s %-10d ; quantity %d\n", "ten spaces", 5, 120); 
          ^

你的第二個printf語句不會引發運行時異常,但只有第一個參數將被顯示。你可以做

System.out.printf("%-2d: %s %d%n", i, "some text here/n", 1); 

閱讀:Formatter