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

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

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

  1. public class Polynomial {
  2. private Term head; //header before first item
  3. private Term tail; //trailer after last item
  4. private int size; // number of elements in Polynomial
  5. //constructor of empty Polynomial
  6. public Polynomial(){
  7. head = new Term();
  8. tail = new Term();
  9. head.next = tail;
  10. tail.prev = head;
  11. } // end empty Polynomial constructor
  12. //Term class
  13. private static class Term {
  14. private int exp;
  15. private double coeff;
  16. private Term next;
  17. private Term prev;
  18. //constructor of empty Term
  19. public Term() {
  20. this.exp = -1;
  21. this.coeff = 0.0;
  22. }// end empty Term constructor
  23. //constructor of term with exponent and coefficient
  24. public Term(int e, double c){
  25. this.exp = e;
  26. this.coeff = c;
  27. }//end constructor of term with exponent and coefficient
  28. //getters of exponent and coefficient
  29. public int getExp() {return exp;}
  30. public double getCoeff() {return coeff;}
  31. //setters of exponent and coefficient
  32. public void setExp(int e) {exp = e;}
  33. public void setCoeff(double c) {coeff = c;}
  34. //getters of pointers of Polynomial terms
  35. public Term getPrev() {return prev;}
  36. public Term getNext() {return next;}
  37. //setters of pointers of Polynomial terms
  38. public void setPrev(Term p) {prev=p;}
  39. public void setNext(Term n) {next=n;}
  40. }// end Term class
  41. //addterm method
  42. public void addTerm(int e, double c){
  43. Term last = tail.prev;
  44. Term temp = new Term(e, c);
  45. temp.next = tail;
  46. temp.prev = last;
  47. tail.prev = temp;
  48. last.next = temp;
  49. size++;
  50. }// end addTerm method
  51. public int size() {return size;}
  52. public boolean isEmpty() {return size==0;}
  53. public static void main(String[] args) throws IOException {
  54. // TODO Auto-generated method stub
  55. FileReader fin = new FileReader("Test.txt");
  56. Scanner src = new Scanner(fin);
  57. Scanner lineTokenizer = new Scanner(src.nextLine());
  58. int lineNum = 0;
  59. Polynomial p1 = new Polynomial();
  60. while (src.hasNextLine()) {
  61. lineNum++;
  62. while (lineTokenizer.hasNextInt()){
  63. p1.addTerm(lineTokenizer.nextInt(), lineTokenizer.nextInt()) ;
  64. }
  65. lineTokenizer.close();
  66. src.close();
  67. }

}

vohkndzv

vohkndzv1#

只需使用bufferedreader,然后拆分行以分隔数字:

  1. BufferedReader reader = new BufferedReader(new FileReader("Test.txt"));
  2. String line;
  3. while((line = reader.readLine()) != null) {
  4. String[] nums = line.split(" ");
  5. //get each num from nums and cast it to integer using Integer.parseInt()
  6. }

相关问题