8

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#?

prinsJoe
  • 683
  • 3
  • 7
  • 16

7 Answers7

16

You can call String.format explicitly:

System.out.println(String.format(
    "My Integer equals %d, and the other one equals %d", myInt, myInt2));
Servy
  • 202,030
  • 26
  • 332
  • 449
9

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);
DT7
  • 1,615
  • 14
  • 26
  • Thanks, that was just a simple example of the printf. I'm still trying to get used to Stack Overflows convention when answering questions :) –  Nov 18 '13 at 19:31
2

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);
DT7
  • 1,615
  • 14
  • 26
Ankit Rustagi
  • 5,539
  • 12
  • 39
  • 70
2

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));
Nikoloz
  • 453
  • 1
  • 3
  • 11
1

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.

matt
  • 9,113
  • 3
  • 44
  • 46
0
int myInt = 10;
int myInt2 = 20;

System.out.println("My Integer equals " + myInt + ", and the other one equals " + myInt2);
user2972135
  • 1,361
  • 2
  • 8
  • 10
0

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.

Ahmed Hamdy
  • 2,547
  • 1
  • 17
  • 23