我正在编写一个包含文本文件的类程序,其中包含以下内容:
1 3 2 4 3 2
1 2 2 7 3 2
添加
我想将前两行中的每一行复制到单独的多项式中 (LinkedLists)。我可以让扫描器对整个文件中的所有整数进行标记,并将所有内容复制到一个多项式中,但我想在第一行中读取,停止,然后将第二行整数复制到单独的多项式中。我不知道如何在每行结束时停止扫描仪。有什么建议吗?
这是我的代码(相关部分位于底部的主要部分)。
public class Polynomial {
private Term head; //header before first item
private Term tail; //trailer after last item
private int size; // number of elements in Polynomial
//constructor of empty Polynomial
public Polynomial(){
head = new Term();
tail = new Term();
head.next = tail;
tail.prev = head;
} // end empty Polynomial constructor
//Term class
private static class Term {
private int exp;
private double coeff;
private Term next;
private Term prev;
//constructor of empty Term
public Term() {
this.exp = -1;
this.coeff = 0.0;
}// end empty Term constructor
//constructor of term with exponent and coefficient
public Term(int e, double c){
this.exp = e;
this.coeff = c;
}//end constructor of term with exponent and coefficient
//getters of exponent and coefficient
public int getExp() {return exp;}
public double getCoeff() {return coeff;}
//setters of exponent and coefficient
public void setExp(int e) {exp = e;}
public void setCoeff(double c) {coeff = c;}
//getters of pointers of Polynomial terms
public Term getPrev() {return prev;}
public Term getNext() {return next;}
//setters of pointers of Polynomial terms
public void setPrev(Term p) {prev=p;}
public void setNext(Term n) {next=n;}
}// end Term class
//addterm method
public void addTerm(int e, double c){
Term last = tail.prev;
Term temp = new Term(e, c);
temp.next = tail;
temp.prev = last;
tail.prev = temp;
last.next = temp;
size++;
}// end addTerm method
public int size() {return size;}
public boolean isEmpty() {return size==0;}
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
FileReader fin = new FileReader("Test.txt");
Scanner src = new Scanner(fin);
Scanner lineTokenizer = new Scanner(src.nextLine());
int lineNum = 0;
Polynomial p1 = new Polynomial();
while (src.hasNextLine()) {
lineNum++;
while (lineTokenizer.hasNextInt()){
p1.addTerm(lineTokenizer.nextInt(), lineTokenizer.nextInt()) ;
}
lineTokenizer.close();
src.close();
}
}
答案 0 :(得分:0)
只需使用BufferedReader,然后将行拆分为不同的数字:
BufferedReader reader = new BufferedReader(new FileReader("Test.txt"));
String line;
while((line = reader.readLine()) != null) {
String[] nums = line.split(" ");
//get each num from nums and cast it to integer using Integer.parseInt()
}