Java 在一行中打印多个字符变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19169185/
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
Print multiple char variables in one line?
提问by Kaptain
So I was just wondering if there was a way to print out multiple char
variables in one line that does not add the Unicode together that a traditional print statement does.
所以我只是想知道是否有一种方法可以char
在一行中打印出多个变量,而不像传统的打印语句那样将 Unicode 添加在一起。
For example:
例如:
char a ='A';
char b ='B';
char c ='C';
System.out.println(a+b+c); <--- This spits out an integer of the sum of the characters
采纳答案by Oliver Charlesworth
System.out.println(a+""+b+""+c);
or:
或者:
System.out.printf("%c%c%c\n", a, b, c);
回答by Sotirios Delimanolis
The println()
method you invoked is one that accepts an int
argument.
println()
您调用的方法是一种接受int
参数的方法。
With variable of type char
and a method that accepts int
, the char
s are widenedto int
s. They are added up before being returned as an int
result.
使用类型的变量char
和接受 的方法int
,将char
s扩展为int
s。在作为int
结果返回之前将它们相加。
You need to use the overloaded println()
method that accepts a String
. To achieve that you need to use String
concatenation. Use the +
operator with a String
and any other type, char
in this case.
您需要使用println()
接受 a的重载方法String
。要实现这一点,您需要使用String
串联。在这种情况下,将+
运算符与 aString
和任何其他类型char
一起使用。
System.out.println(a + " " + b + " " + c); // or whatever format
回答by Kaushik Sivakumar
System.out.print(a);System.out.print(b);System.out.print(c) //without space
System.out.print(a);System.out.print(b);System.out.print(c) //无空格
回答by Cold
This will serve : System.out.println(String.valueOf(a) + String.valueOf(b) + String.valueOf(c));
.
这将服务:System.out.println(String.valueOf(a) + String.valueOf(b) + String.valueOf(c));
。
回答by rob
System.out.println(new StringBuilder(a).append(b).append(c).toString());
回答by barjak
You can use one of the String constructors, to build a string from an array of chars.
您可以使用 String 构造函数之一从字符数组构建字符串。
System.out.println(new String(new char[]{a,b,c}));