繁体   English   中英

什么是Java相当于在C#中打印值?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM