【问题标题】:Print multiple char variables in one line?在一行中打印多个 char 变量?
【发布时间】:2013-10-10 17:47:31
【问题描述】:

所以我只是想知道是否有一种方法可以在一行中打印出多个 char 变量,而不会像传统的 print 语句那样将 Unicode 添加在一起。

例如:

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

【问题讨论】:

  • 你想要一个String,而不是把三个字符加在一起。 char 是一个无符号的 16 位整数。

标签: java char


【解决方案1】:
System.out.println(a+""+b+""+c);

或:

System.out.printf("%c%c%c\n", a, b, c);

【讨论】:

  • 那很快。看起来很简单。谢谢
  • 我会在笨拙的字符串连接上使用 StringBuilder(只是一种偏好),但 printf 答案是 +1。
【解决方案2】:

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

对于char 类型的变量和接受int 的方法,chars 是widenedints。它们在作为int 结果返回之前相加。

您需要使用接受String 的重载println() 方法。为此,您需要使用String 连接。将+ 运算符与String 和任何其他类型一起使用,在本例中为char

System.out.println(a + " " + b + " " + c); // or whatever format

【讨论】:

    【解决方案3】:

    System.out.print(a);System.out.print(b);System.out.print(c) //没有空格

    【讨论】:

      【解决方案4】:

      这将提供:System.out.println(String.valueOf(a) + String.valueOf(b) + String.valueOf(c));

      【讨论】:

        【解决方案5】:
        System.out.println(new StringBuilder(a).append(b).append(c).toString());
        

        【讨论】:

          【解决方案6】:

          您可以使用 String 构造函数之一,从字符数组构建字符串。

          System.out.println(new String(new char[]{a,b,c}));
          

          【讨论】:

            猜你喜欢
            • 2016-06-23
            • 1970-01-01
            • 2021-12-13
            • 2014-06-28
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多