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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 14:41:51  来源:igfitidea点击:

Print multiple char variables in one line?

javachar

提问by Kaptain

So I was just wondering if there was a way to print out multiple charvariables 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 intargument.

println()您调用的方法是一种接受int参数的方法。

With variable of type charand a method that accepts int, the chars are widenedto ints. They are added up before being returned as an intresult.

使用类型的变量char和接受 的方法int,将chars扩展ints。在作为int结果返回之前将它们相加。

You need to use the overloaded println()method that accepts a String. To achieve that you need to use Stringconcatenation. Use the +operator with a Stringand any other type, charin 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}));