如何使用数组 return String.format
How to return String.format with arrays
当我打印 class 的一个实例时,该实例被引用为 "null" 因为我 return "null",我如何格式化 toString [=21] =] 所以它将 return 我在这个函数中实际写的内容:
public String toString()
{
System.out.print(this.coefficient);
for(int i=0; i<26;i++)
{
if(degrees[i] == 1)
{
System.out.print(variables[i]);
}
if(degrees[i]>1)
{
System.out.print(variables[i] + "^" + degrees[i]);
}
}
System.out.println('\n');
return null;
}
例如,它必须return "m1 = 13a^2b^3"
(它是一个多项式)
而是 returns "13a^2b^3 m1 = null"
不是直接打印 String
的每个组件,而是使用 StringBuilder
:
连接它们
public String toString()
{
StringBuilder s = new StringBuilder();
s.append(this.coefficient);
for (int i = 0; i < 26; i++)
{
if (degrees[i] == 1)
{
s.append(variables[i]);
}
else if (degrees[i] > 1)
{
s.append(variables[i]).append('^').append(degrees[i]);
}
}
return s.toString();
}
使用字符串生成器。
无论您在哪里使用 System.out.println
而不是
StringBuilder temp=new StringBuilder();
temp.append();// Add here the content what you are printing with Sysout
// at the end
return temp.toString();
当我打印 class 的一个实例时,该实例被引用为 "null" 因为我 return "null",我如何格式化 toString [=21] =] 所以它将 return 我在这个函数中实际写的内容:
public String toString()
{
System.out.print(this.coefficient);
for(int i=0; i<26;i++)
{
if(degrees[i] == 1)
{
System.out.print(variables[i]);
}
if(degrees[i]>1)
{
System.out.print(variables[i] + "^" + degrees[i]);
}
}
System.out.println('\n');
return null;
}
例如,它必须return "m1 = 13a^2b^3"
(它是一个多项式)
而是 returns "13a^2b^3 m1 = null"
不是直接打印 String
的每个组件,而是使用 StringBuilder
:
public String toString()
{
StringBuilder s = new StringBuilder();
s.append(this.coefficient);
for (int i = 0; i < 26; i++)
{
if (degrees[i] == 1)
{
s.append(variables[i]);
}
else if (degrees[i] > 1)
{
s.append(variables[i]).append('^').append(degrees[i]);
}
}
return s.toString();
}
使用字符串生成器。 无论您在哪里使用 System.out.println
而不是
StringBuilder temp=new StringBuilder();
temp.append();// Add here the content what you are printing with Sysout
// at the end
return temp.toString();