java扫描器-作为有限的数据集读入每一行

1dkrff03  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(349)

我正在为类编写一个程序,该类接收一个文本文件,其中包含以下内容:
1 3 2 4 3 2
1 2 2 7 3 2
添加
我想把前两行中的每一行都复制成单独的多项式(linkedlist)。我可以让扫描器标记整个文件中的所有int,并将所有内容复制到一个多项式中,但是我想读入第一行int,停止,然后将第二行int复制到一个单独的多项式中。我不知道如何在每行末尾停止扫描仪。有什么建议吗?
这是我的代码(相关部分在底部的main中)。

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();

}

}

vohkndzv

vohkndzv1#

只需使用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()
}

相关问题