Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java printing a String containing an integer

I have a doubt which follows.

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

Output: M11

But I want to get it printed M2 instead of M11. I couldn't number++ as the variable is involved with a for loop, which gives me different result if I do so and couldn't print it using another print statement, as the output format changes.

Requesting you to help me how to print it properly.

like image 897
Harish Raj Avatar asked Nov 18 '12 19:11

Harish Raj


2 Answers

Add a bracket around your sum, to enforce the sum to happen first. That way, your bracket having the highest precedence will be evaluated first, and then the concatenation will take place.

System.out.println("M"+(number+1));
like image 75
Rohit Jain Avatar answered Oct 31 '22 19:10

Rohit Jain


Try this:

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

Where %n is a newline

like image 26
Óscar López Avatar answered Oct 31 '22 17:10

Óscar López