# Polynomial LinkedList from Text File (Modification)

• November 26th, 2011, 11:23 PM
javaNewb37
Polynomial LinkedList from Text File (Modification)
I want to modify the below code to read the Polynomial Terms from a text file (vs. hard-coded values)

Furthermore, read data from text file in the format:

P1 = 3 5 1 -1 0 8

P2 = 5 6 2 -1 1 7 0 -4

etc...

Name the values P(x) and input the remaining data... Any advice?

Code :

```  import java.util.*; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.text.*;   public class PolynomialTest { private Monomial head; private double TOLERANCE = 0.00000001;   /***** the Monomial (inner) class ********************************/   private class Monomial { private DecimalFormat precision = new DecimalFormat("#.####"); private int exp; // coeff * x^exp private double coeff; private Monomial next;   public Monomial(int exp, double coeff, Monomial next) { this.exp = exp; this.coeff = coeff; this.next = next; } public String toString() { String form = precision.format(Math.abs(coeff));   if(exp == 0) return form ; else if(exp == 1) return form + "*x"; else return form +"*x^" + exp; } public boolean equals(Monomial mono) { return exp == mono.exp && coeff == mono.coeff; }   }   public PolynomialTest() { head = null; }   /** * Adds a new term into the polynomial, assuming that the polynomial * is sorted in order from smallest to largest exponent. */ public void addTerm(int exp, double coeff) { if( Math.abs(coeff) < TOLERANCE ) return;   if( head == null || exp < head.exp ) { head = new Monomial(exp, coeff, head); return; }   Monomial cur = head; Monomial prev = null;   while( cur != null && exp > cur.exp) { prev = cur; cur = cur.next; } if( cur == null || exp != cur.exp ) prev.next = new Monomial(exp, coeff, cur); else { cur.coeff += coeff; if( Math.abs(cur.coeff) < TOLERANCE ) if(prev != null) prev.next = cur.next; else head = head.next; } }   public String toString() { StringBuffer sb = new StringBuffer();   for(Monomial tmp = head; tmp != null; tmp = tmp.next) if(tmp.coeff < 0 ) sb.append(" - " + tmp.toString()); else sb.append(" + " + tmp.toString());   return sb.toString(); }   /** * Adds two polynomials * The method does not change the original polynomial. */ public PolynomialTest add(PolynomialTest poly) { PolynomialTest res = clone();   for(Monomial tmp = poly.head; tmp != null; tmp = tmp.next) res.addTerm(tmp.exp, tmp.coeff);   return res; }   public PolynomialTest clone() { PolynomialTest res = new PolynomialTest();   for(Monomial tmp = head; tmp != null; tmp = tmp.next) res.addTerm(tmp.exp, tmp.coeff);   return res; }   public boolean equals(PolynomialTest poly) { Monomial tmp1 = head; Monomial tmp2 = poly.head;   while(tmp1 != null && tmp2 != null) { if( !tmp1.equals(tmp2) ) return false; tmp1 = tmp1.next; tmp2 = tmp2.next; } return true; }   /** * Multiplies by a number * The method does not change the original polynomial. */ public PolynomialTest multiply(double num) { PolynomialTest res = clone();   for(Monomial tmp = res.head; tmp != null; tmp = tmp.next) tmp.coeff *= num;   return res; }   /** * Returns a new polynomial that is the derivative of this polynomial. */ public PolynomialTest diff() { PolynomialTest res = new PolynomialTest();   for(Monomial tmp = head; tmp != null; tmp = tmp.next) { if(tmp.exp != 0) res.addTerm(tmp.exp - 1, tmp.coeff * tmp.exp ); }   return res; }   /** * Computes the polynomial at x = value */ public double eval(double value) { double res = 0;   for(Monomial tmp = head; tmp != null; tmp = tmp.next) { res += tmp.coeff * Math.pow(value, tmp.exp); }   return res; }       public static void main(String[] args)     { PolynomialTest first = new PolynomialTest(); PolynomialTest second = new PolynomialTest();   System.out.println( "first" ); first.addTerm(1, 2.1); first.addTerm(4, 2); first.addTerm(3, 1); first.addTerm(0, 1.3); first.addTerm(4, 0.3); System.out.println( first ); System.out.println( );   System.out.println( "second" ); second.addTerm(4, -2.3); second.addTerm(2, 1); second.addTerm(0, -1.3); second.addTerm(1, 0.3); System.out.println( second ); System.out.println( );   System.out.println( "compare first with second" ); System.out.println( first.equals(second) ); System.out.println( "compare first wih first" ); System.out.println( first.equals(first) ); System.out.println( );   System.out.println( "add first and second" ); PolynomialTest third = first.add(second); System.out.println( third ); System.out.println( first ); System.out.println( second ); System.out.println( );   System.out.println( "multiply first by 0.2" ); PolynomialTest fourth = first.multiply(0.2); System.out.println( fourth ); System.out.println( first ); System.out.println( );   System.out.println( "differentiate first" ); PolynomialTest diff = first.diff(); System.out.println( diff ); System.out.println( first ); System.out.println( );   System.out.println( "eval first at x = 1.5" ); System.out.println( first.eval(1.5) ); System.out.println( );   String content = new String(); String name = new String(); File file = new File("test.txt"); LinkedList<String> list = new LinkedList<String>();     try { Scanner sc = new Scanner(new FileInputStream(file)); while (sc.hasNext()) { name = sc.next(); content = sc.nextLine(); list.add(content);     }   sc.close(); } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); } catch (Exception e) { e.printStackTrace(); System.out.println("\nProgram terminated Safely..."); }     Iterator<String> i = list.iterator(); while (i.hasNext()) { System.out.println(name + i.next() + "\n");   }   } }```
• November 27th, 2011, 01:05 AM
murphym18
Re: Polynomial LinkedList from Text File (Modification)
I think I can help you but I'm pretty amateur at this. I wrote code which essentially does the same thing and it works (with glitches I haven't gotten around to fixing yet). I highly doubt I used the best tools in the Java API. Regardless I'll show you basically what I did.

My strategy was to load the text data into a BufferedReader. A BufferedReader is just a fancy data type that takes the contents of a text file and loads into RAM. Next I grabbed all of the characters in between the spaces and new lines and processed them.

With this strategy your polynomials will not be given nice names like P1 and P2. your polynomials will be loaded into an array of polynomials. so you will need to use an array index number instead.

this code requires that the text file containing the polynomial's information be set up special. It assumes that it will put an integer exponent value followed by a space followed by a double coefficient value. It also assumes that each line defines a different polynomial. Here's an example:
Quote:

3 0.5 2 4.12 1 8 12 3.3
2 16.15 1 13.2 -1 2

A text file containing only those numbers exactly as shown should load the following two polynomials:
p1 = 0.5^3 + 4.12^2 + 8 + 3.3^12
p2 = 16.5^2 + 13.2 + 2^-1

Code :

``` public static PolynomialTest[] loadLevelFromFile(String polyFileLocation) throws IOException{ File polyFile = new File(polyFileLocation); return loadFromFile(polyFile); }   public static PolynomialTest[] loadFromFile(File polyFile) throws IOException{   int i, j, k; //for indexing i = k = 0; j = 1; //i and j are for finding the terms, k is for keeping track of the current ArrayList index // a container that can hold as many polynomials as you want ArrayList<PolynomialTest> thePolys = new ArrayList<PolynomialTest>();   //takes the file object, which is just a file location on the mechine, and loads its contents into ram BufferedReader polyFileReader = new BufferedReader(new FileReader(polyFile));   //takes the first line of that file and puts it in the string called currentLine String exponent, coefficient; // for the character sequence between spaces and new lines String currentLine = polyFileReader.readLine(); while (!(currentLine == null)){ while( !currentLine.substring(j-1, j).matches(" ")){ if (j < currentLine.length()){ j = j + 1; }else{ break; } } exponent = currentLine.substring(i , j); i = j; while( !currentLine.substring(j-1, j).matches(" ")){ if (j < currentLine.length()){ j = j + 1; }else{ break; } } coefficient = currentLine.substring(i , j);   thePolys.add(new PolynomialTest()); thePolys.get(k).addTerm(Integer.parseInt(exponent), Double.parseDouble(coefficient));   currentLine = polyFileReader.readLine(); }   PolynomialTest[] result = (PolynomialTest[]) thePolys.toArray(); return result; }```

I did not test this code and I wrote it rather fast but it does show the concept. It most likely has bugs. My implementation of similar code required that each line ended with a space and that the entire text document ended with a blank line.

If you have a copy of Bruce Eckel's thinking in Java 4th edition laying around I recommend you look through the chapter on I/O( that's where I learned ).If you don't have a copy, the author has the third edition on his website, free to download. You can find a download link here: Bruce Eckel's Free Electronic Books