Perry Smith

Java Questions & Answers

Home / Java Q & A Archive Page 3 / Java Q & A Archive

Tuesday, 02-Feb-99 18:52:50

209.156.201.3 writes:

Hi,
Would anyone like to help out a struggling student. I'm working on the following program and when I test it using p.show() for example, the output shows that I've only read one Object into the Vector, even though I input more. The object are Terms of a Polynomial example: Term (coeff, exp). I'd really appreciate any help.

      import java.io.*;
      import java.util.*;
      class Polynomial
      { public Polynomial()
      public static Polynomial readPoly (BufferedReader in) throws IOException {
      Polynomial TempP = new Polynomial();
      String line = new String();
      int i, total_terms = 0;
      System.out.println("-----------");
      while ((line = in.readLine()) != null) {
      StringTokenizer data = new StringTokenizer(line,",");
      total_terms = data.countTokens();
      for (i=0; i < total_terms/2; i++){
      int c = Integer.parseInt(data.nextToken());
      int e = Integer.parseInt(data.nextToken());
      Term tempTerm = new Term(c,e);
      TempP.pvec.addElement(tempTerm); }
      }
      TempP.nterms = TempP.pvec.size();
      System.out.println("Size of vector = " + TempP.pvec.size());
      TempP.Show();
      return(TempP);
      }


      public void Show() throws ArrayIndexOutOfBoundsException {
      for (int i=0;i < nterms; i++)
      { t = (Term)pvec.elementAt(i);
      System.out.print(t.getCoeff());
      System.out.println("X^" + t.getExp());
      }
      }

      private int nterms;
      private Vector pvec = new Vector();
      private Term t;
      }

Response
Thursday, 04-Feb-99 20:33:14

152.172.204.192 writes:

Assuming your Term class functions correctly, I don't see any problems. Are you separating all of your input terms with commas? Is there any particular reason that you are using recursive variables though? You defined TempP as an instance variable in the class of it's own type. I can't think of any problems with that, but I also see no reason for you doing that. I believe the convention is to declare the global variables near the top of the class.

MikeD


Home / Java Q & A Archive Page 3 / Java Q & A Archive