Polynomial and Stringtokenizer

I'm stuck on a homework problem involving a polynomial. The part I'm stuck on is where you're given a string in the form of a polynomial and you need to split it up into it's different terms.
One constructor, Polynomial(String poly), is somewhat tricky. For this constructor you must extract the required information from the string passed as an argument. Stylistic issues are important in defining the valid parameters for this constructor.
    * ax^n+bx^(n-1)+c1x^(n-2)+...+d , the string is a valid polynomial.
    * No two terms have the same exponent.
    * No terms with coefficient 0 (2x^2+1 is valid input for 2x^2+0x^1+1).
    * Terms with coefficient of 1 omits the 1 (x^3+x^2 is valid).
    * The x^1 term omits the exponent 1 (2x^3+3x is valid).
    * The x^0 term, the constant term, omits everything but the coeficient (2x^3+3x+1 is valid).
    * There are no occurrences of contiguous plus and minus signs (+- and -+ not allowed).
    * The leading positive sign on the initial term is unnecessary: 5x^2+4x+2 is valid, not +5x^2+4x+2
    * There are no duplicate terms, i.e., there is at most one term for a given power.I think I know where to start, that's using a StringTokenizer. But from there I'm lost. Any help would be greatly appreciated.

Ordinarily, I would advise against using StringTokenizer for parsing mathematical expressions, but your requirements are so simple that it should suffice.
You have one or more terms separated by plus or minus signs--that's your delimiter. You have to keep the delimiter (instead of discarding it as StringTokenizer usually does) so you can apply the correct sign to the following term. And you have to handle an optional minus sign at the beginning of the expression (i.e., the first "term" might be the empty string, and should be ignored).
Does that help?

Similar Messages

  • Form feed, null and StringTokenizer

    is form feed recognized as null when using the StringTokenizer?
    i currently have my StringTokenizer set with a blank space and i am attempting to read until the value is (EOF) null and while it hasMoreTokens. the text file that i am reading from spans across several pages. my code falls out of my loop when it hits the last space on my first page.

    a form feed (\f) is not a null but that shouldn't be stopping the StringTokenizer, I suspect that the manner in which you're reading in the data may be the culprit. Try to use the BufferedReader class to read your file.
    V.V.

  • FileReader and StringTokenizer

    what I'm trying to do is to read String and Double date in a txt document here my code:
    import java.io.*;
    import java.util.*;
    public class partie1 {
         static final int limite_colones=10;
         static final int limite_lignes=10;
         static final int limite_matieres=5;
         static final int limite_eleves=15;
         static final String titre="�cole secondaire Cartierville";
         static String nomEleve[]=new String[limite_eleves];
         static double notesEleve[][]=new double[limite_eleves][limite_matieres];
         public static void main(String[] args)throws IOException {
              String ligne,ficEleve="c:/ficEleves.txt";
              BufferedReader ficnomlogique=new BufferedReader(new FileReader(new File(ficEleve)));
              while ((ligne=ficnomlogique.readLine())!=null){
                   StringTokenizer ligneTemp=new StringTokenizer (ligne,":");
                   for(int i=0;i<15;i++){
                        nomEleve=ligneTemp.nextToken();
                        System.out.println(nomEleve[i]);
                        for(int j=0;j<5;j++){
                             notesEleve[i][j]=Double.parseDouble(ligneTemp.nextToken());
                             System.out.println(notesEleve[i][j]);
    and this is what they give me as error message:
    Alain
    100.0
    90.0
    88.0
    60.0
    65.0
    Exception in thread "main" java.util.NoSuchElementException
    at java.util.StringTokenizer.nextToken(Unknow Source)
    at partiel.main(partie1.java:20)
    so i understand that it doesnt change ligne or doesnt do the for correctly but i can't figure where is my mistake.
    thank for your help

    What do the records in the file look like?
    This code:
    for(int i=0;i<15;i++){
        nomEleve=ligneTemp.nextToken();
    System.out.println(nomEleve[i]);
    for(int j=0;j<5;j++){
    notesEleve[i][j]=Double.parseDouble(ligneTemp.nextToken());
    System.out.println(notesEleve[i][j]);
    will call nextToken() on each line 15 + (15 * 5) = 90 times.
    Does each line contain 90 tokens?

  • File I/O and StringTokenizer

    Hi
    This may be really simple, but I seem to have problem here. I am reading a txt file using FileReader and I am just printing it out. The txt file has lots of lines. What I want now is to take just the lines which has an = sign on it( there should be only one =) and print just that. This line in the txt file is the form key=value(a hashtable) I need to printout just those lines which are of these form key=value and ignore all the lines. I know I should use the StringTokenizer, but how do I read the.txt file and check if there is any blank line or illegal line and select the line with key=value and print it.
    Please let me know.
    Thanks

    yourStuff() is a snippet that you will change with your source code.
    The regular expression is:
    "^\\w+=\\w+$"
    It means: "from starting data input position (^) followed with one or more char in set [a-zA-Z0-9_] (\\w+), followed with an '=', followed with one or more char (\\w+) till the end of data input ($)".
    It assures no more than one '=' in a line but since you can have blankspaces surrounding this char use that: "^\\w+\\s*=\\s*\\w+$".
    The method "matches()" means "exactly matches" and using anchors: ^ and $, ie; exactly matches from start to end of data input.

  • Faster split than String.split() and StringTokenizer?

    First I imrpoved performance of split by replacing the String.split() call with a custom method using StringTokenizer:
                    final StringTokenizer st = new StringTokenizer(string, separator, true);
                    String token = null;
                    String lastToken = separator; //if first token is separator
                    while (st.hasMoreTokens()) {
                        token = st.nextToken();
                        if (token.equals(separator)) {
                            if (lastToken.equals(separator)) { //no value between 2 separators?
                                result.add(emptyStrings ? "" : null);
                        } else {
                            result.add(token);
                        lastToken = token;
                    }//next tokenBut this is still not very fast (as it is one of the "hot spots" in my profiling sessions). I wonder if it can go still faster to split strings with ";" as the delimiter?

    Yup, for simple splitting without escaping of separators, indexOf is more than twice as fast:
        static private List<String> fastSplit(final String text, char separator, final boolean emptyStrings) {
            final List<String> result = new ArrayList<String>();
            if (text != null && text.length() > 0) {
                int index1 = 0;
                int index2 = text.indexOf(separator);
                while (index2 >= 0) {
                    String token = text.substring(index1, index2);
                    result.add(token);
                    index1 = index2 + 1;
                    index2 = text.indexOf(separator, index1);
                if (index1 < text.length() - 1) {
                    result.add(text.substring(index1));
            }//else: input unavailable
            return result;
        }Faster? ;-)

  • Missing Value using HashMap and StringTokenizer

    class StringToken
         String Message = "a b Germany";
         HashMap <String,String> map;
    StringTokenizer token;
         public StringToken()
              try
              token = new StringTokenize(Message);
                   map = new HashMap <String,String>();
                   map.put("a","Adelaide");
                   map.put("b","Auckland");
    while (token.hasMoreToken())
                        System.out.print (map.get(pesan.nextToken())+" ");          
              catch(Exception e)
         public static void main(String[] args)
              new StringToken();
    The output like this :
    Adelaide Auckland null
    What i want like this:
    Adelaide Auckland Germany
    The problem is,How to display all value of Message? cos There's no Germany key..i want to make some condition like this, if there's no key in the Hashmap, the value still displayed originally..
    At my code the problem is, if there's no key in hashmap,output wont display the word..
    Thanks Guys...

    Two options:
    1) Instead of
    System.out.print(map.get(pesan.nextToken()));do
    String token = pesan.nextToken();
    String value = map.get(token);
    if (value==null) value = token;
    System.out.print(value);2) Implement a new Map which provides this behavior.
    Cheers

  • String and stringtokenizer problem

    Hi,
    String s=new String(null);
    is it possible or not?
    StringTokenizer st=new StringTokenizer(null,",");
    is it possible or not?

    hi sudha,
    when u write
    String s=new String(null); is wrong. Just b'coz the method of String(byte()) that are from java.lang.String will match with your declared method.
    so it will have to clashing ...so u will get ERROR dear.
    Regards
    saM

  • StringTokenizer vs. split and empty strings -- some clarification please?

    Hi everybody,
    I posted a question that was sort of similar to this once, asking if it was best to convert any StringTokenizers to calls to split when parsing strings, but this one is a little different. I rarely use split, because if there are consecutive delimiters, it gives empty strings in the array it returns, which I don't want. On the other hand, I know StringTokenizer is slower, but it doesn't give empty strings with consecutive delimiters. I would use split much more often if there was a way to use it and not have to check every array element to make sure it isn't the empty string. I think I may have misunderstood the javadoc to some extent--could anyone explain to me why split causes empty strings and StringTokenizer doesn't?
    Thanks,
    Jezzica85

    Because they are different?
    Tokenizers are designed to return tokens, whereas split is simply splitting the String up into bits. They have different purposes
    and uses to be honest. I believe the results of previous discussions of this have indicated that Tokenizers are slightly (very
    slightly and not really meaningfully) faster and tokenizers do have the option of return delimiters as well which can be useful
    and is a functionality not present in just a straight split.
    However. split and regex in general are newer additions to the Java platform and they do have some advantages. The most
    obvious being that you cannot use a tokenizer to split up values where the delimiter is multiple characters and you can with
    split.
    So in general the advice given to you was good, because split gives you more flexibility down the road. If you don't want
    the empty strings then yes just read them and throw them away.
    Edited by: cotton.m on Mar 6, 2008 7:34 AM
    goddamned stupid forum formatting

  • Need code example for StringTokenizer to hashmap...

    I am creating a rolodex with name, phone, address, city, state. The data will be saved to a delimited file. When the app begins I have to read the file to get the records into memory. My GUI will list the names. The user should be able to click on one of the names to open a dialog box in which all the fields will appear and wil be editable.
    I need some assistance with design...
    I think I should use BufferedReader and StringTokenizer for reading the file in. Then perhaps store the records in a hashmap(need help with that - Is hashmap the thing to use? Maybe arraylist instead? How do i do it?) The records should be stored sorted by name in memory and in the file. Next, I figure I can show the names using a table and hide the other columns, when a cell is clicked I can pop up the dialog box with all the goodies in it. When I save it should be to memory, how do I do that? Then when the app closes I will write out using PrintWriter.
    There are other things going on, buttons, listeners, etc. but the basic design is what I need advice on. Any ideas are welcome and appreciated!

    From the name to get the record, clearly you need a effecient lookup mechnism.
    HashMap does hash lookup, that is right, but HashMap does NOT do ordering.
    TreeMap does binary lookup, TreeMap also does ordering.
    There you go the basic design.
    --lichu                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Text, Searching, and Replacing

    After looking at the API's for String, StringBuffer, and StringTokenizer I am not sure how to accomplish my task. I have a StringBuffer that contains the contents of a file. I want to search in that StringBuffer for text '<servlet-name>Name</servlet-name>', then continue searching to the next occurence of '</servlet>', then insert several lines of text before '</servlet>'. The text I am searching is not always in the same position in each file I am reading. I sure would appreciate a point in the right direction.
    Thanks much!
    Zach

    Since you're working with an XML file the cleanest but disruptive and heavyweight solution would be to parse the file into a DOM tree, modify the tree and render it back out to a file. Let me know if you want to discuss this approach further.
    If you prefer to proceed with text-only modification, you could do the following:
    1 Read the file into a StringBuffer
    2 Get a String view using StringBuffer.toString()
    3 Use String.indexOf() twice to find the right place to insert your additional lines
    4 Use StringBuffer.insert() to add your text
    5 Write the StringBuffer back to a file.

  • Really advanced StringTokenizer query...

    Just wondering... Why isn't StringTokenizer in the java.text package? It is a utility, of course, but it is more so (IMO) a text-manipulation class.
    Aside from "cuz Sun said so", of course.

    It could be completely arbritrary. But the following is from the javadocs for java.text, and StringTokenizer does not fit.
    Package java.text
    Provides classes and interfaces for handling text, dates, numbers, and messages in a manner independent of natural languages.

  • I am missing something regarding redirection and Stream

    Using Scanner, am I able to redirect on the fly? I am familiar with redirection in C. Is redirection in Java similar? Do I have to redirect in the following manner:
    java myprogram < mytestfile.txtor can I redirect on the fly with Scanner?
    Also, is end of file in Java the same as when I provide Scanner input and hit return?
    What I desire to do is allow both console use and redirection. If the user prefers redirection, then my program will use Scanner and StringTokenizer to parse each line of the file, ignoring /n and sending a long concatenated string as input further along. If the user prefers console, then I have a method that will read a file and the program continues.
    Edited by: 832844 on Feb 24, 2011 8:29 AM

    jverd wrote:
    >
    If you mean a ? b : c, see [url http://download.oracle.com/javase/tutorial/java/nutsandbolts/op2.html]here and/or google for java ternary operator.
    What I would ideally like to do is exactly the following: Allow console input using the keyboard and Scanner or allow redirection into Scanner from a file.That's pretty vague.
    This is not a vague question at all. My desire is to allow a user of my program at their leisure to run the program and provide input from the keyboard. The program will obviously, for simplicity sake, use Scanner. Now if the user happens to have multiple input they do not want to type into the console using their keyboard, they can feel free to have the option of redirecting input from a file.
    Now this is all to be done using:
    Scanner keyboard = new Scanner(System.in)That is it, there are no multiple instances of Scanner. This is the front door of the program and it has the responsibility to accept the following:
    * single-line input from the keyboard with a return following each line of input
    * multiple lines of input from the keyboard via a cut and paste operation such as from a file
    * Redirected input from a file that may have commands spanning multiple lines.
    The problem encapsulated clearly for me is this: Right now my front door uses Scanner. It can handle single line input, as in, type something, hit return, and watch the fireworks. however, if I decide to redirect from a file that contains multiple lines of data or cut-n-paste from the file containing multiple lines of data, my program will have a brain fart and see only each line as input. For example:
    Ex. 1
    Keyboard Input:  This is my input (followed by carriage return)
    Response from the program: Nice job
    Ex. 2
    File Input:  Line 1
                    Line 2
                    Line 3
    Response from the program:  I don't understand, I have only partial data
                                             I don't understand, I have only partial data
                                             I don't understand, I have only partial data
    Ex. 3
    Cut-n-Paste: Line 1
                      Line 2
                      Line 3
    Response from the program:  I don't understand, I have only partial data
                                             I don't understand, I have only partial data
                                             I don't understand, I have only partial dataIt is clear I provided valid data in all three examples. The only difference is I chose to split that data across multiple lines where each line is followed by a carriage return. The program had a brain fart and barfed all over my data. This is not what I want to happen.
    So then how can I do this?
    Edited by: 832844 on Feb 24, 2011 10:37 AM

  • How to read a .csv file(excel format) using Java.

    Hi Everybody,
    I need to read a .csv file(excel) and store all the columns and rows in 2d arrays. Then I can do the rest of the coding myself. I would like it if somebody could post their code to read .csv files over here. The .csv file can have different number of columns and different number of rows every time it is ran. The .csv file is in excel format, so I don't know if that affects the code or not. I would also appreciate it if the classes imported are posted too. I would also like to know if there is a way I can recognize how many rows and columns the .csv file has. I need this urgently so I would be very grateful to anybody who has the solution. Thanks.
    Sincerely Taufiq.

    I used this
    BufferedReader in = new BufferedReader (new FileReader ("test.csv"));
    // and                
    StringTokenizer parser = new StringTokenizer (str, ", ");
                    while (parser.hasMoreTokens () == true)
                    { //crap }works like a charm!

  • Changing data in a linked list object.

    hi,
    i'm still pretty new to java, so bear with me if i am making stupid mistakes, heh.
    i'm having trouble with changing data in an object stored in a singly-linked list. i've created a class that will store polynomials in sorted order (descending) in a singly-linked list. each linked list is one polynomial, and each node references to a polynomial object that stores two ints: the coefficient and the exponent of that term.
    i'm having trouble when it comes to 'collecting like terms,' though. here's a rough skeleton of my code:
    public class Polynomial
    private LinkedList polynoList;
    private LinkedListItr Itr;
    private int coeff;
    private int exponent;
    public Polynomial()
    zeroPolynomial();
    } // this constructor sets up an empty linked list
    public Polynomial( int c, int e )
    coeff = c;
    exponent = e;
    } // this creates a Polynomial object storing the two ints
    public void zeroPolynomial()
    polynoList = new LinkedList();
    theItr = polynoList.zeroth();
    } // this method creates the empty linked list and sets the
    //iterator on the zeroth node.
    //various other methods are here, not relevant to my post
    //this next method is the one i am having trouble with.
    //it takes two ints as parameters, the coefficient
    //and the exponent.
    public void insertTerm( int c, int e )
    //...i have a few if/then statements here
    //so that the terms can be inserted in descending order.
    LinkedListItr tester = polynoList.first();
    //the 'tester' iterator is set on the first node
    //this following if statement retrieves the exponent
    //in the current node by casting the information
    //retrieved from the LinkedList retrieve() method
    //into Polynomial, then compares it to the current
    //exponent. if they are equal, i want to add the
    //coefficients.
    if( e == ((Polynomial)tester.retrieve()).getExp() )
    this.coeff = ((Polynomial)tester.retrieve()).getCoeff() + c;
    //a main method goes here wherein the user can insert
    //terms, print the polynomial, etc.
    }//end Polynomial class
    can anyone help me out? the code i'm using compiles correctly, but it does not change the value of the current coeff variable as i'd like to think it should. any input would be GREATLY appreciated, thanks!

    hey,
    thanks for the reply...
    i am sure that ((Polynomial)tester.retrieve()).getExp() will return an int equal to 'e.' i tried this:
    System.out.println("e="+e);
    System.out.println((Polynomial)tester.retrieve()).getExp());
    if( e == ((Polynomial)tester.retrieve()).getExp() ){
    this.coeff = ((Polynomial)tester.retrieve()).getCoeff() + c;
    System.out.println( "this.coeff = " + this.coeff );
    with that, the output showed that e and the getExp() output were the same. it also showed (as output) that this.coeff did change in value, but when i tried this:
    System.out.println( ((Polynomial)tester.retrieve()).getCoeff() )
    to check if the value changed within the object, it didn't. this.coeff changed, but the actual coeff variable in the object didn't.
    any ideas?

  • ObjectFile.load() getting in an infinite loop?

    Hi all,
    I am having problems loading ObjectFiles with Java3D, essentially it appears that the load method of the ObjectFile class gets stuck in some sort of loop. I discovered this since the method would be executing for minutes for something that I assume would not take that long without throwing any exceptions. I have tried loading with a string for the filename, as well as a URL and the result is the same. To ascertain the problem I have been using the Debugger in Netbeans to see the trace.
    I know the Object file must be fine since I can load it fine with a library called JOGLOBJ http://code.google.com/p/joglobj/ . I did suspect it may be something to do with the version of Java3D included with Snow Leopard, but changing the default libraries with the latest version does not change anything.
    File f = new File("woman1.obj");
    URL urlToModel = f.toURI().toURL();
    ObjectFile fl = new ObjectFile();
    Scene s = fl.load(urlToModel);The hang happens at with the call to load. Unfortunately I cant seem to get the source for Java3D to show up in the Debugger, so the Java3D methods calls are not visible. The calls above are to BufferedReader.read then below that are calls to StreamDecoder and below the Java3D calls are to InputStreamReader, BufferedReader and StringTokenizer, then calls to ObjectFile.
    BufferedInputStream.read:308
    StreamDecoder.readBytes:264
    StreamDecoder.implRead:306
    StreamDecoder.read:158
    InputStreamReder.read:167
    BufferedReader.fill:136
    BufferedReader.read:157
    StreamTokenizer.read:486
    StreamTokenizer.nextToken:527
    ObjectFileParser.getToken:99
    ObjectFileParser.skipToNextLine:145
    ObjectFile.readFile:602
    My code:
    I suppose that one alternative is to Build up Java3D objects from the raw vertex data that I have read with JOGLOBJ. Would I need to build Objects such as GeometryArrays. The main reason I wish to use Java3D is for the Vertex Splitting methods that it has, so that I can simplify geometry.
    Thanks,
    Lawrence

    Seems that this is an issue in Java3D when using files from Meshlab which have no EOF character [ Issue 587|https://java3d.dev.java.net/issues/show_bug.cgi?id=587] I guess that the Java3D parser is not robust enough to recognise when the end of file occurs. Would a workaround be to insert an EOF into each obj file manually?

Maybe you are looking for

  • Adding angles in multicam

    In the manual I found instructions on adding an angle to an existing multicam clip. I was able to add it in the angle edtior, but it's not showing in the angle viewer. Any suggestions?

  • Indesign PDF optimization

                Hello, lets say that I want to make Indesign PDF, done from only one image of 50 kb, multiplied 10 times. How can Indesign (or PDF) embed image only once instead od 10 times? So the PDF is 50kb instead of 500 kb? Thank you very much, Toni

  • Trying to set up a new ipod touch

    Keep getting the msg server error, what should we do differently?

  • Software updates- Security&safari 3.1 update... does not boot

    hi everyone, i'm trying to help my room mate out with a problem. he has a mac mini intel 1.66ghz. he does have 2gb ram installed by a apple certified tech a month ago and it is problem free. here's the dirty stuff. so first off, he has a western digi

  • Save files to NAS

    Hi, New to Mac, I just bought an iMac and want to save all iWork file to my NAS how can I do this or would I be better getting Office?? Cheers Dave