[英]What is the Java equivalent to printing values in C#?
在C#中,我可以說:
int myInt = 10;
int myInt2 = 20;
Console.WriteLine("My Integer equals {0}, and the other one equals {1}", myInt, myInt2);
而且我知道如何用Java打印這樣的東西:
int myInt = 10;
System.out.println("My Integer equals " + myInt);
那么如何將這兩者結合起來,以便在Java中,我可以像在C#中那樣打印多個值?
您可以顯式調用String.format
:
System.out.println(String.format(
"My Integer equals %d, and the other one equals %d", myInt, myInt2));
別忘了printf
語句..
int myInt = 0;
int myInt2 = 20;
System.out.printf("My Integers equal %d, and the other one equals %d\n",
myInt, myInt2);
您可以使用+
來顯示多個變量
int myInt = 10;
int myInt2 = 20;
System.out.println("My Integer equals " + myInt
+ "and second integer is " + myInt2);
您可以嘗試MessageFormat類。 您的代碼與C#代碼幾乎相同,應如下所示:
int myInt = 10;
int myInt2 = 20;
System.out.println(MessageFormat.format("My Integer equals {0}, and the other one equals {1}", myInt, myInt2));
閱讀java中字符串的格式: http : //docs.oracle.com/javase/tutorial/essential/io/formatting.html
實質上,您不是在C#中使用基於索引的格式化方法,而是添加按字符串中存在的順序處理的格式說明符。 例如:
System.out.format("My integer equals %d, and the other one equals %d", myInt, myInt2);
Java對不同的值類型使用不同的說明符。 %d
(上面使用)表示整數值。 %s
將是一個字符串, %f
將是一個浮點值,等等。更多詳細信息可以在上面的鏈接中找到。
int myInt = 10;
int myInt2 = 20;
System.out.println("My Integer equals " + myInt + ", and the other one equals " + myInt2);
您可以使用String格式化程序,因此通過處理您的示例,我將執行此操作:
int myInt = 10;
System.out.format("My Integer equals %d %n", myInt);
如果我們將C#代碼轉換為java,它將如下所示:
int myInt = 10;
int myInt2 = 20;
System.out.format("My Integer equals %d, and the other one equals %d %n", myInt, myInt2);
更加進步,你可以格式化浮球%.2f
與格式化INT %03d
等等。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.