Help with Java Calculator Program

Discussion in 'Java' started by DeAndrea Monroe, Oct 27, 2010.

  1. I am writing a calculator program in Java. I just need the basics but
    I'm using a stack. I'm trying to do a nested while loop that counts
    integers that are greater than 9 but I can't seem to get it right. My
    code can be found here: http://code.google.com/p/cschelp/source/list
    DeAndrea Monroe, Oct 27, 2010
    #1
    1. Advertising

  2. DeAndrea Monroe

    Stefan Ram Guest

    DeAndrea Monroe <> writes:
    >I'm trying to do a nested while loop that counts integers
    >that are greater than 9 but I can't seem to get it right.


    for( counter.reset(); integers.hasNext(); )
    if( integers.getNext().isGreaterThan( 9 ))counter.increment();

    »Besides a mathematical inclination, an exceptionally
    good mastery of one's native tongue is the most vital
    asset of a competent programmer.«

    Edsger Wybe Dijkstra
    Stefan Ram, Oct 27, 2010
    #2
    1. Advertising

  3. On Oct 27, 9:37 am, -berlin.de (Stefan Ram) wrote:
    > DeAndrea Monroe <> writes:
    > >I'm trying to do a nested while loop that counts integers
    > >that are greater than 9 but I can't seem to get it right.

    >
    > for( counter.reset(); integers.hasNext(); )
    > if( integers.getNext().isGreaterThan( 9 ))counter.increment();
    >
    >       »Besides a mathematical inclination, an exceptionally
    >       good mastery of one's native tongue is the most vital
    >       asset of a competent programmer.«
    >
    >     Edsger Wybe Dijkstra


    Thanks so much.
    DeAndrea Monroe, Oct 27, 2010
    #3
  4. On Oct 27, 9:41 am, DeAndrea Monroe <> wrote:
    > On Oct 27, 9:37 am, -berlin.de (Stefan Ram) wrote:


    > > for( counter.reset(); integers.hasNext(); )
    > > if( integers.getNext().isGreaterThan( 9 ))counter.increment();


    I'm having problems with that code working.
    DeAndrea Monroe, Oct 27, 2010
    #4
  5. DeAndrea Monroe

    Stefan Ram Guest

    DeAndrea Monroe <> writes:
    >On Oct 27, 9:41 am, DeAndrea Monroe <> wrote:
    >> On Oct 27, 9:37 am, -berlin.de (Stefan Ram) wrote:
    >>>for( counter.reset(); integers.hasNext(); )
    >>>if( integers.getNext().isGreaterThan( 9 ))counter.increment();

    >I'm having problems with that code working.


    It assumes appropriate types of »counter« and »integers«.
    Thus, the operations »reset()«, »hasNext()«, »getNext()«,
    »isGreaterThan( 9 )« and »increment()« usually still need to
    be implemented.
    Stefan Ram, Oct 27, 2010
    #5
  6. I am now getting many errors pertaining to my code. Most of the errors
    say; class, interface, or enum expected. I thought I made classes for
    everything that's being used. I also made a package for
    calculatorEngine, but I'm still getting errors there.
    DeAndrea Monroe, Oct 27, 2010
    #6
  7. > You may not be going at this the best way.
    >
    > I usually start a program by writing something very simple that does a
    > tiny subset of the required behavior, and is only a dozen lines or so.
    >

    The code was given to me in a C++ format, I was just supposed to
    change a few things and make it work with Java. The functions and what
    they do are recognizable but I just can't get them to actually do what
    is stated.
    DeAndrea Monroe, Oct 27, 2010
    #7
  8. On Oct 27, 5:43 pm, DeAndrea Monroe <> wrote:
    > > You may not be going at this the best way.

    >
    > > I usually start a program by writing something very simple that does a
    > > tiny subset of the required behavior, and is only a dozen lines or so.

    >
    > The code was given to me in a C++ format, I was just supposed to
    > change a few things and make it work with Java. The functions and what
    > they do are recognizable but I just can't get them to actually do what
    > is stated.


    I made a few changes to the code and I'm still getting the same
    errors. Is there a way where I can compare C++ code to Java code?
    DeAndrea Monroe, Oct 27, 2010
    #8
  9. On Wed, 27 Oct 2010 15:47:49 -0700, DeAndrea Monroe wrote:

    > On Oct 27, 5:43 pm, DeAndrea Monroe <> wrote:
    >> > You may not be going at this the best way.

    >>
    >> > I usually start a program by writing something very simple that does
    >> > a tiny subset of the required behavior, and is only a dozen lines or
    >> > so.

    >>
    >> The code was given to me in a C++ format, I was just supposed to change
    >> a few things and make it work with Java. The functions and what they do
    >> are recognizable but I just can't get them to actually do what is
    >> stated.

    >
    > I made a few changes to the code and I'm still getting the same errors.
    > Is there a way where I can compare C++ code to Java code?
    >

    Use the mark 1 eyeball?

    More seriously, I've converted C to Java by duplicating the source and
    editing it so that:
    - all globals become class attributes
    - functions become methods
    - constant definitions in the header file get rolled into the class
    as public static final attributes
    - other changes made as needed

    but this does depend for its success on the semi-OO way I've always
    written C, in which a source file, which contains functions and all the
    globals that are used by them has a vague resemblance to a class.


    --
    martin@ | Martin Gregorie
    gregorie. | Essex, UK
    org |
    Martin Gregorie, Oct 28, 2010
    #9
  10. DeAndrea Monroe

    Stefan Ram Guest

    -berlin.de (Stefan Ram) writes:
    >>> On Oct 27, 9:37 am, -berlin.de (Stefan Ram) wrote:
    >>>>for( counter.reset(); integers.hasNext(); )
    >>>>if( integers.getNext().isGreaterThan( 9 ))counter.increment();

    >>I'm having problems with that code working.

    >It assumes appropriate types of »counter« and »integers«.
    >Thus, the operations »reset()«, »hasNext()«, »getNext()«,
    >»isGreaterThan( 9 )« and »increment()« usually still need to
    >be implemented.


    Just for fun, here is a complete program with the above code
    in them method »main«, except that »getNext« was replaced by
    »next«:

    public class Main
    {
    static class Counter
    { int value;
    void reset(){ this.value = 0; }
    void increment(){ if( value >= ++value )
    throw new java.lang.RuntimeException(); }
    public final java.lang.String toString()
    { return java.lang.String.valueOf( value ); }}

    static class Integer
    { int value;
    public Integer( final int value ){ this.value = value; }
    public boolean isGreaterThan( final int value )
    { return this.value > value; }}

    static final Counter counter = new Counter();

    static final java.util.ArrayList<Integer> list =
    new java.util.ArrayList<Integer>();

    static
    { list.add( new Integer( 1 ));
    list.add( new Integer( 11 ));
    list.add( new Integer( 11 ));

    java.lang.Runtime.getRuntime().addShutdownHook
    ( new java.lang.Thread
    ( new java.lang.Runnable()
    { public void run()
    { java.lang.System.out.println( counter ); }})); }

    static final java.util.Iterator<Integer> integers = list.iterator();

    public static void main( final java.lang.String[] args )
    {
    for( counter.reset(); integers.hasNext(); )
    if( integers.next().isGreaterThan( 9 ))counter.increment(); }}

    It prints »2« because in the list, there are 2 numbers
    greater than 9. Thus, it has counted the numbers greater
    than 9.
    Stefan Ram, Oct 28, 2010
    #10
  11. DeAndrea Monroe

    Stefan Ram Guest

    -berlin.de (Stefan Ram) writes:
    >static class Counter
    >{ int value;
    > void reset(){ this.value = 0; }
    > void increment(){ if( value >= ++value )
    > throw new java.lang.RuntimeException(); }
    > public final java.lang.String toString()
    > { return java.lang.String.valueOf( value ); }}


    I say that a class has a »perfect type« encapsulation«, when
    one can change types used in the class so as to enhance it,
    while its interface does not change.

    The above Counter class has a perfect encapsulation of the
    type of »value«. This means, to change it, say, from »int«
    to »long« or to »double«, one has to change the one
    occurence of »int« to »long« or to »double«, respectively,
    and the whole program will immediately work correct again -
    while the counter indeed will be enhanced, i.e., be able to
    count to larger values.
    Stefan Ram, Oct 28, 2010
    #11
  12. DeAndrea Monroe

    markspace Guest

    On 10/27/2010 3:47 PM, DeAndrea Monroe wrote:
    > Is there a way where I can compare C++ code to Java code?



    I have to agree with Martin here. Do you understand C++? Do you
    understand the C++ code you were given? Do you understand Java?

    It seems to me that answering "yes" to all three would be a prerequisite
    to completing your project. At least one of those answers seems like it
    must be "no" at this point.
    markspace, Oct 28, 2010
    #12
  13. >   The above Counter class has a perfect encapsulation of the
    >   type of »value«. This means, to change it, say, from »int«
    >   to »long« or to »double«, one has to change the one
    >   occurence of »int« to »long« or to »double«, respectively,
    >   and the whole program will immediately work correct again -
    >   while the counter indeed will be enhanced, i.e., be able to
    >   count to larger values.


    I think I asked the wrong question. I'm trying to do a loop that takes
    a number, longer than one digit, as a whole. For example, I have a
    case statement that goes up to the number 9 but if the number is 273,
    it will only see the number 2 and ignore the 7 and 3. How would I do
    about writing that loop?
    DeAndrea Monroe, Oct 28, 2010
    #13
  14. On Oct 27, 9:41 pm, markspace <> wrote:
    > On 10/27/2010 3:47 PM, DeAndrea Monroe wrote:
    >
    > >  Is there a way where I can compare C++ code to Java code?

    >
    > I have to agree with Martin here.  Do you understand C++?  Do you
    > understand the C++ code you were given?  Do you understand Java?
    >
    > It seems to me that answering "yes" to all three would be a prerequisite
    > to completing your project.  At least one of those answers seems like it
    > must be "no" at this point.


    I don't understand C++. I haven't taken any courses on it but I do
    understand pieces of it. I partially understand Java, I took a course
    like 3 years ago and I'm being reintroduced to it but I have forgotten
    a few things.
    DeAndrea Monroe, Oct 28, 2010
    #14
  15. DeAndrea Monroe

    Stefan Ram Guest

    DeAndrea Monroe <> writes:
    >I think I asked the wrong question.


    Yes, I guessed so right from the start. That was the reason
    to include the quotation about the English language / mother
    language.

    >I'm trying to do a loop that takes a number, longer than one
    >digit, as a whole. For example, I have a case statement that
    >goes up to the number 9 but if the number is 273, it will
    >only see the number 2 and ignore the 7 and 3. How would I do
    >about writing that loop?


    Well, this can not be answered in some sentences.

    Imagine, someone would ask: Hello, I have a person lying
    here before me and need to exchange his liver, I have a
    knife and a blanket, how can I do this?

    The answer would be: Either you have undergone extensive
    training to do this, then you do not need to ask here, or,
    otherwise, anything one could tell you via this
    communication channel is of no use to you.

    You need a more holistic and more humble approach. You can
    not learn the above in isolation. You need to improve your
    overall language skills. To do this you need to read books
    on the topic and/or visit classes but at a more
    simple/fundamental level first than the one you attempt to
    tackle now. You are attempting to write a simple so-called
    »scanner«, and once you mastered the fundamentals, you can
    read texts about scanner construction or study scanners
    written by others.

    Concentrate on a single language (like C++ or Java) first
    for about 3 years. (Some people need more, some need less.)

    See

    »Teach Yourself Programming in Ten Years - Peter Norvig«

    http://norvig.com/21-days.html

    .
    --

    FWIW: I wrote this about how to implement a simple
    calculator in Java. Your question appears as exercise #4 below.

    (If answering to the following post, one should please not
    quote all of it, but only a few lines one directly refers to.)

    In order to interpret or translate an expression (term), it is
    decomposed into lexical units (tokens, words), which then are
    used by a parser to build symbols and a structured
    representation of the input. This representation then might be
    evaluated or translated into some other representation.

    The syntactial structuring resembles the rules for the
    construction of an expression, which often is given by so-
    called "productions" of the EBNF (extended Backus-Nauer-Form)
    and which sometimes are left-recursive.

    When writing a parser, the left-recursive productions sometimes
    are a worry to the author, because it is not obvious how to
    avoid an infinite recursion. The solution is to rewrite them as
    right-recursive productions.

    The addition with a binary infix Operator, for example, is
    left associative. However, it is simpler to analyze in a
    right-associative manner. Therefore, one analyzes the source
    using right-associative rules and then creates a result
    using a left-associative interpretation.

    A left-associative grammar might be, for example, as follows.

    <numeral> ::= '2' | '4' | '5'.
    <expression> ::= <numeral> | <expression> '+' <numeral>.
    start symbol: <expression>.

    To analyze this using a recursive descent parser, one
    prefers to use the following grammar.

    <numeral> ::= '2' | '4' | '5'.
    <expression> ::= <numeral>[ '+' <expression> ].
    start symbol: <expression>.

    This can be written using iteration as follows.

    <numeral> ::= '2' | '4' | '5'.
    <expression> ::= <numeral>{ '+' <numeral> }.
    start symbol: <expression>.

    However, the product is created in the sense of the
    first grammar. Example code follows.

    class Scan
    { final static String source = "5+4+2)";
    static int pos = 0;
    static char get(){ return source.charAt( pos++ ); }}

    class Parse
    {
    static int numeral(){ return Scan.get() - '0'; }

    static int expression(){ int result = numeral();
    while( '+' == Scan.get() )result += numeral();
    return result; }}

    public class Start
    { public static void main( final String[] args )
    { System.out.println( Parse.expression() ); }}

    To be able to parse expressions with higher
    priority, the grammar can be extended.

    <numeral> ::= '2' | '4' | '5'.
    <product> ::= <numeral> | <product> '*' <numeral>.
    <sum> ::= <product> | <sum> '+' <product>.
    start symbol: <sum>.

    In iterative notation:

    <numeral> ::= '2' | '4' | '5'.
    <product> ::= <numeral>{ '*' <numeral> }.
    <sum> ::= <product>{ '+' <product> }.
    start symbol: <sum>.

    In Java:

    class Scan
    { final static String source = "5+4*2)";
    static int pos = 0;
    static char get( final boolean advance )
    { return source.charAt( advance ? pos++ : pos ); }}

    class Parse
    {
    static int numeral(){ return Scan.get( true ) - '0'; }

    static int product(){ int result = numeral();
    while( '*' == Scan.get( false )){ Scan.get( true ); result *= numeral(); }
    return result; }

    static int sum(){ int result = product();
    while( '+' == Scan.get( true ))result += product();
    return result; }}

    public class Start
    { public static void main( final String[] args )
    { System.out.println( Parse.sum() ); }}

    Exercises

    - What is the output of the above programs?

    - Extend the last grammar and the last program so as
    to handle subtraction.

    - Extend the result of the last exercise in order
    to handle division.

    - Extend the result of the last exercise so that also
    numbers with multiple digits are accepted.

    - Extend the result of the last exercise so that also
    terms in parentheses are accepted. The input "(2+4)*5)"
    should give the result "30".

    - Extend the result of the last exercise so that
    also a unary minus "-" is recognized.

    - Extend the result of the last exercise so that
    more operators and functions are recognized.

    - Extend the result of the last exercise so that
    meaningful error messages are created for all
    inputs that do not fulfill the rules of the input
    language.

    - Extend the result of the last exercise so that the
    error messages also show the location where the error
    was detected. It should be possible to enter an expression
    that spans multiple lines, and an error message should
    contain the number of the line where the error was
    detected.

    See also:

    JEP - Java Mathematical Expression Parser
    http://www.singularsys.com/jep/

    Steven Metsker: Building Parsers with Java.
    Addison-Wesley 2001, ISBN 0201719622.

    A.W. Appel: Modern Compiler Implementation in Java.
    Cambridge University Press 1998, ISBN 0521586542.

    Implementing a scripting engine
    http://www.flipcode.com/articles/scripting_issue01.shtml

    http://compilers.iecc.com/crenshaw/

    http://www.threedee.com/jcm/psystem/p2.zip
    Stefan Ram, Oct 28, 2010
    #15
  16. >   You need a more holistic and more humble approach. You can
    >   not learn the above in isolation. You need to improve your
    >   overall language skills. To do this you need to read books
    >   on the topic and/or visit classes but at a more
    >   simple/fundamental level first than the one you attempt to
    >   tackle now. You are attempting to write a simple so-called
    >   »scanner«, and once you mastered the fundamentals, you can
    >   read texts about scanner construction or study scanners
    >   written by others.


    I apologize if I seem hostile, that is not my intent. I just feel like
    I get mixed messages, some say be agressive and ask what questions
    you're having. At the same time, I'm a little frustrated becaue I have
    been working on this program for like 6 days and I'm still getting
    errors. I don't understand why they are happening or how to fix them
    directly.
    DeAndrea Monroe, Oct 28, 2010
    #16
  17. I have reposted my revised code. I'm getting the errors:

    <identifier> expected
    cannot find symbol
    missing return statement
    incompatible types
    '{' expected
    DeAndrea Monroe, Oct 28, 2010
    #17
  18. DeAndrea Monroe

    markspace Guest

    On 10/27/2010 6:45 PM, DeAndrea Monroe wrote:

    > I don't understand C++. I haven't taken any courses on it but I do
    > understand pieces of it. I partially understand Java, I took a course
    > like 3 years ago and I'm being reintroduced to it but I have forgotten
    > a few things.



    OK, it's good to know where we are at then. I think the first step is
    to understand the C++ program. Could you check that in so we can take a
    look at it? I didn't see it on the Google code site where you linked to
    in your first post.
    markspace, Oct 28, 2010
    #18
  19. On Oct 27, 11:39 pm, markspace <> wrote:
    > On 10/27/2010 6:45 PM, DeAndrea Monroe wrote:
    >
    > > I don't understand C++. I haven't taken any courses on it but I do
    > > understand pieces of it. I partially understand Java, I took a course
    > > like 3 years ago and I'm being reintroduced to it but I have forgotten
    > > a few things.

    >
    > OK, it's good to know where we are at then.  I think the first step is
    > to understand the C++ program.  Could you check that in so we can take a
    > look at it?  I didn't see it on the Google code site where you linked to
    > in your first post.


    It's a handout that was given to me from an instructor.
    DeAndrea Monroe, Oct 28, 2010
    #19
  20. DeAndrea Monroe

    markspace Guest

    On 10/27/2010 8:29 PM, DeAndrea Monroe wrote:
    > I have reposted my revised code. I'm getting the errors:
    >
    > <identifier> expected
    > cannot find symbol
    > missing return statement
    > incompatible types
    > '{' expected


    The first of these that I see occurs on line 111. First, when you give
    us errors, it's good to give the whole error message, so that we can see
    what it is you are really doing.

    Second, that line 111 is:

    while ((!Operator.isEmpty(); evaluate <= Operator.stackTop())

    A. We don't have access to the Operator source file, so there's no way
    to tell if it is correct.

    B. Regardless, the while() statement does not take a ; in its condition
    statement. That's just a syntax error plain and simple.

    You really need to go to your computer lab and hang out there. These
    are questions that absolutely must be take up with your instructor. If
    you don't have access to a computer lab or your instructor off hours,
    then I'd suggest a different school, as you are wasting time and money
    at the current one.
    markspace, Oct 28, 2010
    #20
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Rafael

    Need help with my Calculator program.

    Rafael, Dec 2, 2003, in forum: C Programming
    Replies:
    6
    Views:
    395
    osmium
    Dec 4, 2003
  2. Vijaykumar Dave

    calculator program with memory function

    Vijaykumar Dave, Apr 26, 2007, in forum: C Programming
    Replies:
    10
    Views:
    640
    Vijaykumar Dave
    May 3, 2007
  3. skull
    Replies:
    2
    Views:
    1,016
    luciyahelan
    Dec 1, 2010
  4. Yonih
    Replies:
    4
    Views:
    123
    Yonih
    Jun 25, 2008
  5. JonDoe297
    Replies:
    6
    Views:
    134
    Chris Angelico
    Oct 4, 2013
Loading...

Share This Page