我在程序中使用了三个类:
Term
具有变量系数和指数的类,toString()方法等。Polynome
类,使用ArrayList存储不同的Term
对象。Main
运行程序的类。 我可以toString
在Polynome类中使用ArrayList的方法吗?我正在尝试,但不能。
我需要我的polynome输出如下:[3x ^ 2,3x ^ 1,1x ^ 0]
我真的很困惑,我在调用Term的toString方法,使用for循环分别访问每个术语。
我的代码:
public class Term {
private int coëfficiënt;
private int exponent;
public Term(int coëfficiënt, int exponent) {
this.coëfficiënt = coëfficiënt;
this.exponent = exponent;
}
public int getCoef() {
return coëfficiënt;
}
public int getExp() {
return exponent;
}
public String toString() {
return coëfficiënt + "x^" + exponent;
}
}
Polynome类:
public class Polynoom {
private ArrayList<Term> polynoom;
public Polynoom() {
polynoom = new ArrayList<Term>();
}
public void add(Term term) {
polynoom.add(term);
}
public Term get(int i) {
return polynoom.get(i);
}
public int size() {
return polynoom.size();
}
public String toString() {
// what should I write here?
}
}
主班:
public class opgave3 {
public static void main(String[] args) {
Polynoom polynoom1, polynoom2, sompolynoom;
polynoom1 = new Polynoom();
polynoom1.add(new Term(1, 2));
polynoom1.add(new Term(3, 1));
polynoom1.add(new Term(1, 0));
polynoom2 = new Polynoom();
polynoom2.add(new Term(-1, 3));
polynoom2.add(new Term(2, 2));
polynoom2.add(new Term(-5, 0));
System.out.println("Tests: ");
System.out.println(polynoom1.toString());
for (int i = 0; i < polynoom1.size(); i++) {
System.out.println(polynoom1.get(i).toString());
}
System.out.println(polynoom1.get(0).toString());
}
}
编辑:快速的答案,因为您把您的代码放
return polynoom.toString();
您已指出的地方。然后在您的Main class中,您只需编写
System.out.println(polynoom1);
以所需的格式显示内容。
正如Tenner所说,使用ArrayList的toString()方法来获取所需的输出。但还要确保您的Term类具有自己的有用的toString方法:
public class Term {
private int co, ex;
public Term(int coeff, int exp) {
co = coeff;
ex = exp;
}
@Override
public String toString() {
return co + "x^" + ex;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句