Java 如何打印 2 个整数但不添加它们?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27905851/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to print 2 int(s) but not add them?
提问by F.A
I know this seems like a stupid question (so excuse me). Basically this is what I want to do:
我知道这似乎是一个愚蠢的问题(请原谅)。基本上这就是我想要做的:
int a = 5;
int b = 3;
System.out.print(a+b);
this will give me 8, but is there a way other than putting an empty string inbetween for it to print 5 and 3 (and not by converting the int to a string)?
这会给我 8,但是除了在其间放置一个空字符串来打印 5 和 3(而不是通过将 int 转换为字符串)之外,还有其他方法吗?
Thank you so much.
非常感谢。
回答by Dr. John A Zoidberg
try
尝试
System.out.print(a+""+b)
or
或者
System.out.print(a+" "+b)
if you want a space between them
如果你想要它们之间的空间
回答by Alan
The print method will simply convert its argument to a string and write out the result. Therefore, if you want to display the two numbers concatenated, you will need to do this yourself by converting them to a string (either explicitly, or using "" as you've already mentioned).
print 方法将简单地将其参数转换为字符串并写出结果。因此,如果您想显示连接的两个数字,您需要通过将它们转换为字符串(明确地,或使用您已经提到的“”)来自己完成。
If you want to avoid building the string yourself, you'd probably need to use the printf() method:
如果您想避免自己构建字符串,您可能需要使用 printf() 方法:
System.out.printf("%d%d", a, b);
回答by C0reTex
Java will always execute an arithmetic operator. To avoid this behavior, you need to convert the numbers to string.
Java 将始终执行算术运算符。为了避免这种行为,您需要将数字转换为字符串。
This should work for you:
这应该适合你:
System.out.println("" + a + b);
Because of the empty string at the beginning, Java is going to interpret + as a concatenation operator and joins the values of your variables with the empty string.
由于开头是空字符串,Java 会将 + 解释为连接运算符,并将变量的值与空字符串连接起来。
回答by iwlagn
- User explicit string conversion (not so elegant solution):
- 用户显式字符串转换(不是那么优雅的解决方案):
System.out.print(new Integer(a).toString()+b);
- Use sequential calls to System.out.print (no new line will be added):
- 使用对 System.out.print 的顺序调用(不会添加新行):
System.out.print(a); System.out.print(b);
- Use java.lang.StringBuilder:
- 使用 java.lang.StringBuilder:
import java.lang.StringBuilder; ... StringBuilder sb = new StringBuilder(); sb.append(a); sb.append(b); System.out.print(sb.toString());
回答by Shail
You need to convert the parameter inside the println method into a string literal ,then java compiler would recognize it as a string and will not add two integers.
您需要将 println 方法中的参数转换为字符串文字,然后 java 编译器会将其识别为字符串并且不会添加两个整数。
System.out.println(a+""+b);
or use format method
或使用格式化方法
System.out.format("%d%d",a,b);