简体   繁体   English

Java打印包含整数的String

[英]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 输出: M11

But I want to get it printed M2 instead of M11. 但我想把它打印成M2而不是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. 我无法对++进行编号,因为变量与for循环有关,如果我这样做会给我不同的结果,并且无法使用另一个print语句打印它,因为输出格式会发生变化。

Requesting you to help me how to print it properly. 请求您帮我正确打印。

Try this: 尝试这个:

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

Where %n is a newline %n是换行符

Add a bracket around your sum, to enforce the sum to happen first. 在您的总和周围添加一个括号,以强制首先发生的sum That way, your bracket having the highest precedence will be evaluated first, and then the concatenation will take place. 这样,将首先评估具有最高优先级的bracket ,然后进行concatenation

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

It has to do with the precedence order in which java concatenates the String, 它与java连接String的优先顺序有关,

Basically Java is saying 基本上Java就是这样说的

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

You can overload the precedence just like you do with maths 您可以像对数学一样重载优先级

"M"+(number+1)

This now reads 这现在读了

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

尝试

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

尝试这个:

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

A cleaner way to separate data from invariants: 从不变量中分离数据的更简洁方法:

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

String concatination in java works this way: java中的字符串连接以这种方式工作:

if the first operand is of type String and you use + operator, it concatinates the next operand and the result would be a String. 如果第一个操作数是String类型并且你使用+运算符,它会合并下一个操作数,结果将是一个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. 在这种情况下,因为() paranthesis具有最高优先级,所以括号内的事物将首先被评估。 then the resulting int value would be concatenated with the String literal resultingin a string "M2" 然后生成的int值将与String文字连接,结果为字符串“M2”

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

Here You are using + as a concatanation Operator as Its in the println() method. 这里你在println()方法中使用+作为它的连接运算符。

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));

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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM