Help Needed w/ simple Calculator Program!


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 5 of 5

Thread: Help Needed w/ simple Calculator Program!

  1. #1
    Join Date
    Mar 2005
    Posts
    1

    Exclamation Help Needed w/ simple Calculator Program!

    For some reason, I'm getting an error message when I try to compile the following program. Its a simple calculator program that take three arguments from the command line (two integers and an operator) to preform math problems.



    class Calculator {
    public static void main(String[] arguments) {
    int answer = 0;
    int firstNumber = Integer.parseInt(arguments[0]);
    int secondNumber = Integer.parseInt(arguments[2]);

    if (arguments[1].equals(+)) {
    answer = firstNumber + secondNumber;
    System.out.print(answer);
    }
    else if (arguments[1].equals(-)) {
    answer = firstNumber - secondNumber;
    System.out.print(answer);
    }
    else if (arguments[1].equals(*)) {
    answer = firstNumber * secondNumber;
    System.out.print(answer);
    }
    else if (arguments[1].equals(x)) {
    answer = firstNumber * secondNumber;
    System.out.print(answer);
    }
    else if (arguments[1].equals(/)) {
    answer = firstNumber / secondNumber;
    System.out.print(answer);
    }
    else {
    System.out.println("That is not a valid entry. Please try again.");
    System.out.print("You entered " + firstNumber);
    System.out.print(arguments[1]);
    System.out.print(secondNumber);
    }
    }
    }

    This is the error message:
    Calculator.java:7: illegal start of expression
    if (arguments[1].equals(+)) {
    ^
    Calculator.java:33: ')' expected
    }
    ^

    Thanks ahead of Time!!!

  2. #2
    Join Date
    Mar 2005
    Posts
    3
    Where you have .equals(+) the + needs to be in quotes eg .equals("+")

  3. #3
    Join Date
    Mar 2005
    Location
    Sendling, MUC, .de
    Posts
    100
    Yeah, and not only with the +... ; )

    Well, I just wanted to say that this if...else if...else if... is really ugly. There is the switch statement:
    Code:
    char operator = arguments[1].charAt[0];
    switch (operator) {
      case '+':  answer = firstNumber + secondNumber;
        break;
      case '-':  answer = firstNumber - secondNumber;
        break;
      case '*':  answer = firstNumber * secondNumber;
        break;
      case '/':  answer = firstNumber / secondNumber;
        break;
      default:
        System.out.println("unknown operator '" + operator + "'. Please try again.");
        System.exit();
    }
    System.out.println(answer);
    Ok, this is doing exactly what your code does - in less lines. However, it has the disadvantage of only working with operator(-name)s consisting of exactly one character and there is still considerable duplication of code.

    So, what about having a class for the operator? You could then simply write in main() something like:
    Code:
    Operator op = Operator.get( arguments[1] );
    if (op==null) {
      System.out.println("no such operator: " + arguments[1]);
    } else {
      System.out.println( op.applyTo(firstNumber, secondNumber) );
    }
    With an abstract class Operator (given farther below), you could introduce new operators like
    Code:
    class CombinationsOperator extends Operator {
        public CombinationsOperator() {
          super("outof");
        }
        public int applyTo(int k, int n) {
          if ( (k<0) || (k>n) ) {
            return 0;
          } else if (k==n) {
            return 1;
          } else {
            return applyTo(k, n-1) + applyTo(k-1, n-1);
          }
        }
      }
    which calculates the number of sets with k elements, that are a subset of an n-element-set; as it is mathematically defined (extended to integers rather than only for non-negative integers). Eg. your chances at sweepstakes where you choose 6 numbers out of 49 is 1 : (6 outof 49).

    This is definitely not the most efficient way to compute that number, but
    - it illustrates how to keep code that is not clear at first glance separate from code that does different things and most important: how to make explicit what it does (only in second place: how)
    - it is not a trivial translation into the corresponding java expression (because there is none in this case )
    - it is one of the few (binary) operators I could think of for which it makes sense to choose a symbol that is not only one character (another would be the greatest common divisor gcd, but that you'd rather like to write gcd(a,b). If interested, just tell)

    Now, how are all those marvellous operators organized so that we can simply call Operator.get(symbol)? Well, only one outof many possibilities:
    Code:
    import java.util.*;
    
    public abstract class Operator {
      private static Map operators = new HashMap();
      public Operator(String symbol) {
        operators.put(symbol, this);
      }
      abstract int applyTo(int a, int b);
      public static Operator get(String symbol) {
        return (Operator) operators.get(symbol);
      }
    }
    I know, all that abstract, static, ... might be confusing. But if you later on want a more sophisticated calculator, you have to organize it in a way similar to this. There are still enough (unsolved) problems, for example what about operators that aren't binary and infix? Eg. -42 (unary, prefix) or 7! (factorial; unary, postfix). What about braces like in (1+2)*3 ? This is not easy and you're better off if you have the what-and-how-to-do-when-symbol-is-x separated from that and can concentrate on one thing at a time.

    --
    p.s.: to get this example working, you must somewhere once instantiate your XxxxOperator classes, eg. in main(): new CombinationsOperator(); Thats enough, you need not assign this newly created CombinationsOperator to some variable.

    p.p.s.: @sjalle: when compiled under 1.5, it says:
    Note: Operator.java uses unchecked or unsafe operations.
    Note: Recompile with -Xlint:unchecked for details.
    Ain't that great?
    Last edited by meisl; 03-24-2005 at 08:04 PM.

  4. #4
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560
    p.p.s.: @sjalle: when compiled under 1.5, it says:
    Right away it appears like the tiger is somewhat nervous about the 'generic' hashmap
    eschew obfuscation

  5. #5
    Join Date
    Mar 2005
    Location
    Sendling, MUC, .de
    Posts
    100
    Yes, it is! Or was it me?

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center