println()方法中的字符串连接

时间:2014-03-14 10:43:42

标签: java arrays string

  • println()方法在打印时添加值也是数组

    int a = 5;
    int b = 3;
    int c[] = {1,2};
    System.out.println(a+b);            //8
    System.out.println(a+b+" ");        //8
    System.out.println(c[0]+c[1]);      //3
    System.out.println(c[0]+c[1]+" ");  //3
    

为什么会给出不同的结果?

4 个答案:

答案 0 :(得分:1)

在java中使用带有字符串的“+”运算符添加任何数据类型的变量(int,float,double)时是否也可以是“”,其他数据类型的变量也将隐式转换为String并且所有数据类型都被追加而不是添加。

In first case a+b: 
both are integers, so it directly adds up to give 8.

In second case a+b+ " ":
first two operands are integers it adds up to give 8 but since third one is a string 
(" ")
it i.e. 8 gets converted to "8" then get concatenated with " " i.e. "8"+" " to give 8

  In third case c[0]+c[1] : 
  Here both are integers so 1+2 = 3

  In fourth case c[0]+c[1]+ " " :
 Here first two integers added to give 1+2 = 3 but since third is a string so 3 gets    converted to "3" and gets concatenated to "3" + " " to give 3

  But if below is the case: 
  i.e. 
  System.out.println(" " + a+b);
  Then answer would be 53. 
  Because: First operand is string so, both 5 and 3 get converted to "5" and "3" and     concatenate with " " to give " "+"5"+"3"= 53

答案 1 :(得分:0)

首先,System.out.println可以将int作为参数。

这意味着任何int值(例如int未加前缀的String总和,即使为空)也会打印已计算的表达式。

其次,您的第二个println语句实际上会打印出来:

8 

(注意后面的空格)

...如果您当然没有声明array a

最后,要打印array内容,请使用:

int[] a = {1,2};
System.out.println(Arrays.toString(a)); 

<强>输出

[1, 2]

答案 2 :(得分:0)

System.out.println(a+b+" ")打印5 3的说明错误!

你可能意味着System.out.println(a+" "+b)确实打印了5 3

话虽如此,这是对每个println陈述的正确“解释”:


System.out.println(a+b);
System.out.println(5+3);
System.out.println(8);

System.out.println(a+" "+b);
System.out.println(5+" "+3);
System.out.println("5 "+3);
System.out.println("5 3");

System.out.println(c[0]+c[1]);
System.out.println(1+2);
System.out.println(3);

System.out.println(c[0]+c[1]+" ");
System.out.println(1+2+" ");
System.out.println(3+" ");
System.out.println("3 ");

答案 3 :(得分:0)

&#34; +&#34;运算符对于不同类型的行为不同。对于整数值,它将参数求和(如1 + 1给出2),对于字符串值,它将它们连接起来(例如&#34; 1&#34; +&#34; 1&#34;给出&#34; 11&#34; )。在你的问题中你可能想要连接它们,所以你必须先将它们转换为String。

但是,我建议你使用StringBuilder进行字符串连接,如下所示:

int a = 5;
int b = 3;

StringBuilder sb = new StringBuilder();
System.out.println(sb.append(a+b).toString()); // 8

sb = new StringBuilder();
System.out.println(sb.append(a).append(b).toString()); // 53

sb = new StringBuilder();
System.out.println(sb.append(a).append(" ").append(b).toString()); // 5 3

// ... and so on.