Java print string containing integer

I have a doubt that follows.

public static void main(String[] args) throws IOException{ int number=1; System.out.println("M"+number+1); } 

Conclusion: M11

But I want him to type M2 instead of M11. I couldn’t specify the number ++, because the variable is connected to the for loop, which gives me a different result if I do this, and could not print it using another print statement, as the output format changes.

A request to help me print it correctly.

+6
source share
8 answers

Try the following:

 System.out.printf("M%d%n", number+1); 

Where %n is the newline character

+10
source

Add a bracket around your sum to run sum . That way, your highest priority bracket will be rated first and then concatenation .

 System.out.println("M"+(number+1)); 
+4
source

It is related to the priority order in which java concatenates the string,

Basically java says

  • "M"+number = "M1"
  • "M1"+1 = "M11"

You can overload priority as you would with math.

 "M"+(number+1) 

Now he reads

  • "M"+(number+1) = "M"+(1+1) = "M"+2 = "M2"
+4
source

Try

 System.out.println("M"+(number+1)); 
+2
source

Try the following:

 System.out.println("M"+(number+1)); 
+2
source

A cleaner way to separate data from invariants:

 int number=1; System.out.printf("M%d%n",number+1); 
+2
source
  System.out.println("M"+number+1); 

String concatenation in java works as follows:

if the first operand is of type String and you use the + operator, it will concatenate the next operand, and the result will be a string.

try

  System.out.println("M"+(number+1)); 

In this case, when parathesis () has the highest priority, things inside the brackets will be evaluated first. then the resulting int value will be combined with the string literal obtained in the string "M2"

+2
source

System.out.println("M"+number+1);

Here you use + as the concatenation operator as in the println() method.

To use + to carry out the amount, you need to specify a High priority, which you can do by closing it with brackets, as shown below:

System.out.println("M"+(number+1));

+2
source

All Articles