有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!


共 (5) 个答案

  1. # 1 楼答案

    记住,在Java中,操作符(比如+)可以重载。这意味着它将根据操作数做不同的事情。对于+,有(至少)两种选择:整数加法字符串串联

    选择哪个重载更取决于左侧操作数。此外,与非字符串操作数的字符串串联可能会导致自动转换为字符串

    整个过程将从左到右进行评估,如下所示:

    x + y + " = " + y + x
    
    3 + 5 + " = " + 3 + 5     // 3+5 chooses the integer addition overload of +
    
    8 + " = " + 3 + 5         // 8 + " = " chooses string concatenation
    "8" + " = " + 3 + 5       // so 8 is converted to "8" first
    "8 = " + 3 + 5            // and then concatenated with " = "
    
    "8 = " + "3" + 5          // now 3 is converted to "3"
    "8 = 3" + 5               // and concatenated with "8 ="
    
    "8 = 3" + "5"             // finally 5 is converted to "5"
    "8 = 35"                  // and concatenated with the rest
    

    FWIW,正是这种模糊性让我不喜欢隐式转换1

    1-In C#。我喜欢Python中的它:-)

  2. # 2 楼答案

    第一个+在两个数字之间,所以结果是8。第二个数字两边都有字符串,所以数字被转换成字符串并连接在一起。加号操作符绑定到最左边,并从左到右求值。如果希望最后一个加法是数字,那么表达式应该在括号()中

  3. # 3 楼答案

    输出为“8=53”的原因是:

    x + y + " = " + y + x
    

    是从左到右计算的,如果我们把它一块一块地分解:

    x + y = 8
    
    8 + " = " = "8 = "
    
    "8 = " + y = "8 = 5"
    
    "8 = 5" + x = "8 = 53"
    

    编译器就是这样得到答案的:)

  4. # 4 楼答案

    第一部分被解释为整数加法,但在第二部分(正如您介绍的字符串)中,它被解释为整数加法和字符串串联

    假设你想要8 = 8

    试试看

    System.out.println(x + y + " = " + (y + x));
    

    如果你想要3 + 5 = 5 + 3

    然后我会用String.format作为 在

     System.out.println (String.format ("%d + %d = %d + %d", x, y, y, x));
    
  5. # 5 楼答案

    output is "8=53". Why does the first x+y gets evaluated and the last y and x expression gets printed?

    因为第一个x + y没有附加字符串,所以整数计算就完成了。第二个值由于" = " +而被追加到字符串中,因此它们被打印为单独的值

    要证明这一点,只需:

        System.out.println("" + x + y + " = " + x + y);
    

    输出将是:

    35 = 35