2015-11-04 43 views
0

在Java中,我要掃描用戶的formatString中和inputDouble一倍如下:的Java printf的格式字符串參數

Scanner scan = new Scanner(System.in); 
System.out.println("Enter formating string and double to format:"); 
String formatString = scan.next(); 
Double inputDouble = scan.nextDouble(); 

但現在,讓我們說我只有

String formatString = "%.2f"; 
Double inputDouble = 42.424242; 

我會使用System.out.printf();根據formatString格式化inputDouble。喜歡的東西:

System.out.printf("Formated double: '%s'", formatString, inputDouble); 

這樣一些形式:

System.out.printf("Formated double: 'magicGoesHere'", formatString, inputDouble); 
在這種特殊情況下

所以,我想看看輸出:

Formated double: 42.42 

是否有可能以某種方式?感謝

+1

'的String.format(formatString中,inputDouble)',然後利用產生的'String'在'System.out' – MadProgrammer

回答

1
System.out.printf("Formated double: '%s'", String.format (formatString, inputDouble)); 
+1

或者:System.out.printf(String.format(「Formatic double:'%s'」,formatString),inputDouble)'。 –

+0

謝謝,工作得很好 –

1

斯普利特呼叫成幾部分:

System.out.print("Formated double: '"); 
System.out.printf(formatString, inputDouble); 
System.out.print("'"); 
+0

好的技巧,沒有想到它,但我真的很喜歡它,謝謝:) –