Java printing a String containing an integer

2019-03-25 14:20发布

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.

9条回答
走好不送
2楼-- · 2019-03-25 14:31

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

Here You are using + as a concatanation Operator as Its in the println() method.

To use + to do sum, You need to Give it high Precedence which You can do with covering it with brackets as Shown Below:

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

查看更多
啃猪蹄的小仙女
3楼-- · 2019-03-25 14:36
  System.out.println("M"+number+1);

String concatination in java works this way:

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

try

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

In this case as the () paranthesis have the highest precedence the things inside the brackets would be evaluated first. then the resulting int value would be concatenated with the String literal resultingin a string "M2"

查看更多
beautiful°
4楼-- · 2019-03-25 14:37

Try

System.out.println("M"+(number+1));
查看更多
smile是对你的礼貌
5楼-- · 2019-03-25 14:37

A cleaner way to separate data from invariants:

int number=1;
System.out.printf("M%d%n",number+1);
查看更多
唯我独甜
6楼-- · 2019-03-25 14:37

If you perform + operation after a string, it takes it as concatenation:

"d" + 1 + 1     // = d11 

Whereas if you do the vice versa + is taken as addition:

1 + 1 + "d"     // = 2d 
查看更多
聊天终结者
7楼-- · 2019-03-25 14:39

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));
查看更多
登录 后发表回答