In C#, I can say:
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:
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#?
You can call String.format
explicitly:
System.out.println(String.format(
"My Integer equals %d, and the other one equals %d", myInt, myInt2));
Dont forget the printf
statements..
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. Your code which is almost the same as your C# code should look something like this:
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
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. 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. %d
(used above) indicates integer values. %s
would be a string, %f
would be a floating-point value, etc. More details can be found in the link above.
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:
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:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.