public String toString()
{
String str;
str = "The test scores in descending order are \n";
for(int i = 0; i < data.length; i++)
{
str = str + data[i] + " ";
}
str = str + "\nThe average is " + mean;
return str;
}
此 java 代码按我的代码的降序返回分数。但让我失望的是返回“str”的方式。我的理解是 'str' 的返回值是 (str + "\nThe average is "+ mean)。因为这是我最后更新的'str'值,它会将'str'更新为“The test scores in descending order are” First, Second the loop, then last "str + "\nThe average is "+ mean".所以最后即使我们更新了 str 几次,实际打印的 'str' 也只会是 "str + "\n平均值是 "+ mean"。请解释为什么程序最终打印出来了
考试成绩从高到低依次为 70 80 ..........(元素值)
(然后返回平均值信息)
最佳答案
因为命令是
str = str + "\nThe average is " + mean;
这意味着,附加到 str
中的所有内容并将结果存储在 str
中。如果是
str = "\nThe average is " + mean;
它会替换 str
中已有的所有内容。
关于Java toString() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27131035/