加错答案

You*_*f N 7 java oop object

public class Container {
    private int value;
    public Container(int value){
        this.value=value;
    }
    public int getValue(){
        return this.value;
    }
    public int sum(Container c){
        return this.value+c.getValue();
    }
    public void main(){
        Container c1=new Container(1);
        Container c2=new Container(2);
        System.out.println("sum: " + c1.getValue()+c2.getValue());
        System.out.println("sum: " + c1.sum(c2));
    }
}
Run Code Online (Sandbox Code Playgroud)

当我运行此代码时,我得到以下结果:

public class Container {
    private int value;
    public Container(int value){
        this.value=value;
    }
    public int getValue(){
        return this.value;
    }
    public int sum(Container c){
        return this.value+c.getValue();
    }
    public void main(){
        Container c1=new Container(1);
        Container c2=new Container(2);
        System.out.println("sum: " + c1.getValue()+c2.getValue());
        System.out.println("sum: " + c1.sum(c2));
    }
}
Run Code Online (Sandbox Code Playgroud)

预期是:

sum: 12
sum: 3
Run Code Online (Sandbox Code Playgroud)

有谁知道我为什么得到这些结果?

azu*_*rog 9

当您将+运算符与a一起使用时String,它将其视为连接,而不是加法,并且Java从左到右评估操作,因此"sum: " + c1.getValue()+c2.getValue()被评估为

"sum: " + 1 + 2
"sum: 1" + 2
"sum: 12"
Run Code Online (Sandbox Code Playgroud)

如果要先使整数加法,则需要添加括号:

System.out.println("sum: " + (c1.getValue() + c2.getValue()));
Run Code Online (Sandbox Code Playgroud)