我试图从列表中读取多项式,从 main 方法并将它们作为对象传递给 Polynomial.class 中的数组列表。在那里我应该拆分它们并创建一个包含单项式的节点链表,以便稍后我可以对多项式进行数学运算。然而,我设法从文件中读取多项式并将它们传递给 Polynomial 类的构造函数中的数组列表;构造函数中的数组列表显示大小为 1,这使得(就我的知识水平而言)无法将它们拆分为单项式并创建链接的节点链。
这是一个大学项目。
//the mail class
public class MainClass {
public static void main(String[] args) {
Polynomial poly;
ArrayList <Polynomial> polyList = new ArrayList<> ();
String str;
try {
File inputFile = new File ("polynomial.txt");
Scanner scanner = new Scanner (inputFile);
while (scanner.hasNext()) {
str = scanner.nextLine();
poly = new Polynomial(str);
polyList.add(poly);
}
scanner.close();
} catch (FileNotFoundException ex) {
System.out.println("File not found!!");
}//end of catch
}
}
//here is the Polynomial class
import java.util.ArrayList;
public class Polynomial {
public Polynomial (String poly) {
ArrayList<String> polyList = new ArrayList<>();
polyList.add(poly);
System.out.println(polyList.size());
}
这是实际输入:
2x^2+4x+5
7x^2+12
4x^2+7x+6
我得到了一个大小为 1 的 arrayList polyList,但我拥有输入中的所有元素。
您正在构造函数中声明新的 ArrayList。所以每次它都会创建一个新的数组列表并将该值添加到当前数组列表中。所以列表大小总是需要的。我想不是将大小打印到 Polynomial 类中,而是可以在主类中打印它:例如:
public class MainClass {
public static void main(String[] args) {
Polynomial poly;
ArrayList <Polynomial> polyList = new ArrayList<> ();
String str;
try {
File inputFile = new File ("polynomial.txt");
Scanner scanner = new Scanner (inputFile);
while (scanner.hasNext()) {
str = scanner.nextLine();
poly = new Polynomial(str);
polyList.add(poly);
}
scanner.close();
// ################## Print it here ###########
// Actual size
// ###########################################
System.out.println(polyList.size());
} catch (FileNotFoundException ex) {
System.out.println("File not found!!");
}//end of catch
}
}
还可以学习如何使用 IDE(eclips/netbeans/IDEA)调试 java。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句