简体   繁体   English

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

[英]What is the Java equivalent to printing values in C#?

In C#, I can say: 在C#中,我可以说:

 int myInt = 10;
 int myInt2 = 20;
 Console.WriteLine("My Integer equals {0}, and the other one equals {1}", myInt, myInt2);

And I know how to print things in Java like this: 而且我知道如何用Java打印这样的东西:

 int myInt = 10;
 System.out.println("My Integer equals " + myInt);

So how do I combine the two so that in Java, I can print multiple values just like I would in C#? 那么如何将这两者结合起来,以便在Java中,我可以像在C#中那样打印多个值?

You can call String.format explicitly: 您可以显式调用String.format

System.out.println(String.format(
    "My Integer equals %d, and the other one equals %d", myInt, myInt2));

Dont forget the printf statements.. 别忘了printf语句..

int myInt = 0;
int myInt2 = 20;

System.out.printf("My Integers equal %d, and the other one equals %d\n",
                               myInt, myInt2);

You can use + to display multiple variables 您可以使用+来显示多个变量

int myInt = 10;
int myInt2 = 20;
System.out.println("My Integer equals " + myInt 
                    + "and second integer is " + myInt2);

You may try MessageFormat class. 您可以尝试MessageFormat类。 Your code which is almost the same as your C# code should look something like this: 您的代码与C#代码几乎相同,应如下所示:

int myInt = 10;
int myInt2 = 20;
System.out.println(MessageFormat.format("My Integer equals {0}, and the other one equals {1}", myInt, myInt2));

Read up on formatting of strings in java: http://docs.oracle.com/javase/tutorial/essential/io/formatting.html 阅读java中字符串的格式: http//docs.oracle.com/javase/tutorial/essential/io/formatting.html

Essentially, instead of using the index-based formatting approach in C#, you add format specifiers which are processed in the order they exist in the string. 实质上,您不是在C#中使用基于索引的格式化方法,而是添加按字符串中存在的顺序处理的格式说明符。 For example: 例如:

System.out.format("My integer equals %d, and the other one equals %d", myInt, myInt2);

Java uses different specifiers for different value types. Java对不同的值类型使用不同的说明符。 %d (used above) indicates integer values. %d (上面使用)表示整数值。 %s would be a string, %f would be a floating-point value, etc. More details can be found in the link above. %s将是一个字符串, %f将是一个浮点值,等等。更多详细信息可以在上面的链接中找到。

int myInt = 10;
int myInt2 = 20;

System.out.println("My Integer equals " + myInt + ", and the other one equals " + myInt2);

You can use String formatter, so by working on your example, I will do this: 您可以使用String格式化程序,因此通过处理您的示例,我将执行此操作:

int myInt = 10;
System.out.format("My Integer equals %d %n", myInt);

And if we converted the C# code to java, it will look like: 如果我们将C#代码转换为java,它将如下所示:

int myInt = 10;
int myInt2 = 20;
System.out.format("My Integer equals %d, and the other one equals %d %n", myInt, myInt2);

even more advancing, you can format the float with %.2f and format the int with %03d and much more. 更加进步,你可以格式化浮球%.2f与格式化INT %03d等等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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