Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Page 1 of 2 12 LastLast
Results 1 to 25 of 26

Thread: problem with calculator

  1. #1
    Junior Member
    Join Date
    Feb 2014
    Posts
    19
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Exclamation problem with calculator

    hey guys i got a problem with this program.I m supposed to make a calculator using stacks but it seems that i m stack. i can t get the right recognition for () and {} []
    any tips?
    its not necessary to use all these symbols.just a simple () will do .here s the program
    package stackscalc;
     
    import java.util.Scanner;
    import java.util.Stack;
    import java.util.EmptyStackException;
     
     
    class Arithmetic
    {
    int length;
    Stack stk;
    String exp,
    postfix;
     
    Arithmetic(String s)
    {
        stk = new Stack();
        exp = s;
        postfix = "";
        length = exp.length();
     
    }
    boolean isBalance()
    {
        boolean fail = false;
        int index = 0;
     
        try
        {
            while (index < length)
            {
                char ch = exp.charAt(index);
     
                switch(ch)
                {
                    case ')':
                        stk.pop();
                    break;
     
                    case '(':
                        stk.push(new Character(ch));
                    break;
     
                    default:
                    break;
                }
                    index++;
            }
        }
        catch(EmptyStackException e)
        {
            fail = true;
        }
            return stk.empty() && !fail;
    }
    void postfixExpression()
    {
        String token = "";
        Scanner scan = new Scanner(exp);
        stk.clear();
     
        while(scan.hasNext())
        {
            token = scan.next();
            char current = token.charAt(0);
     
            if (isNumber(token))
            {
                postfix = postfix + token + " ";
            }
            else if(isParentheses(current))
            {
                if(current == '(')
                {
                    stk.push(current);
                }
                else
                {
                    Character ch = (Character)stk.peek();
                    char nextToken = ch.charValue();
     
                    while(nextToken != '(')
                    {
                        postfix = postfix + stk.pop() + " ";
     
                        ch = (Character)stk.peek();
     
                        nextToken = ch.charValue();
                    }
                        stk.pop();
                }
            }
            else
            {
                if(stk.empty())
                {
                    stk.push(current);
                }
                else
                {
                    Character ch = (Character)stk.peek();
                    char top = ch.charValue();
     
                    if(hasHigherPrecedence(top, current))
                    {
                        stk.push(current);
                    }
                    else
                    {
                        ch = (Character)stk.pop();
     
                        top = ch.charValue();
     
                        stk.push(current);
     
                        stk.push(top);
                    }
                }
            }
        }
        try
        {
            Character ch = (Character)stk.peek();
            char nextToken = ch.charValue();
     
            while(isOperator(nextToken))
            {
                postfix = postfix + stk.pop() + " ";
                ch = (Character)stk.peek();
                nextToken = ch.charValue();
            }
        }catch(EmptyStackException e){}
    }
    boolean isNumber(String s)
    {
        try
        {
            int Num = Integer.parseInt(s);
        }
        catch(NumberFormatException e)
        {
            return false;
        }
            return true;
    }
    void evaluateRPN()
    {
        Scanner scan = new Scanner(postfix);
        String token = "";
        stk.clear();
     
        while(scan.hasNext())
        {
            try
            {
            token = scan.next();
            if (isNumber(token))
            {
                stk.push(token);
            }
            else
            {
                char current = token.charAt(0);
                double t1 = Double.parseDouble(stk.pop().toString());
                double t2 = Double.parseDouble(stk.pop().toString());
                double t3 = 0;
     
                switch(current)
                {
                    case'+':
                    {
                        t3 = t2 + t1;
                        stk.push(t3);
                        break;
                    }
                    case'-':
                    {
                        t3 = t2 - t1;
                        stk.push(t3);
                        break;
                    }
                    case'*':
                    {
                        t3 = t2 * t1;
                        stk.push(t3);
                        break;
                    }
                    case'/':
                    {
                        t3 = t2 / t1;
                        stk.push(t3);
                        break;
                    }
                    default:
                    {
                        System.out.println("Reverse Polish Notation was unable to be preformed.");
                    }
                }
          }
     
            }
     
            catch(EmptyStackException e){}
        }
    }
    String getResult()
    {
        return stk.toString();
    }
     
    int stackSize()
    {
        return stk.size();
    }
     
    boolean isParentheses(char current)
    {
        if((current == '(') || (current == ')'))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
     
    boolean isOperator(char ch)
    {
        if((ch == '-'))
        {
            return true;
        }
        else if((ch == '+'))
        {
            return true;
        }
        else if((ch == '*'))
        {
            return true;
        }
        else if((ch == '/'))
        {
            return true;
        }
        else
        {
     
        }
            return false;
    }
     
    boolean hasHigherPrecedence(char top, char current)
    {
        boolean HigherPre = false;
     
        switch(current)
        {
        case '*':
            HigherPre = true;
        break;
     
        case '/':
            HigherPre = true;
        break;
     
        case '+':
     
            if((top == '*') || (top == '/') || (top == '-'))
            {
                 HigherPre = false;
            }
            else
            {
                 HigherPre = true;
            }
     
        break;
     
        case'-':
            if((top == '*') || (top == '/') || (top == '-'))
            {
                HigherPre = false;
            }
            else
            {
                HigherPre = true;
            }
        break;
     
       default:
                System.out.println("Higher Precedence Unsuccessful was unable to be preformed.");
       break;
        }
     
    return HigherPre;
    }
     
    String getPostfix()
    {
        return postfix;
    }
    }


  2. #2
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: problem with calculator

    Welcome! Please read this topic to learn how to post code correctly and other useful info for new members.

  3. #3
    Junior Member
    Join Date
    Feb 2014
    Posts
    19
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: problem with calculator

    oh sorry its just that i have to give this assignment in 10 days and i m kinda nervous!i fixed though thank you!
    any suggestions guys?it gives me error and i don t know what i did wrong

  4. #4
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: problem with calculator

    Provide a sample run. Either copy and paste the result from your own console or type out something like:

    Enter this:

    Got this:

    Should be this:

    Whichever approach you choose, be sure to describe or show what the desired answer should be.

  5. #5
    Junior Member
    Join Date
    Feb 2014
    Posts
    19
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: problem with calculator

    yes guys i m sorry you are right.i have a class and our instructor after like 30-40 hours of java wanted us to make a calculator using 2 stacks and i struggle to make it.i m newbie to java.he doesn t want swing just the code.i ll try a bit more and get back to you with more results.i tried the search button but i didn t find any tutorial on how to make it

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: problem with calculator

    Also posted at: calculator using stacks
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: problem with calculator

    What are you struggling with? If you're getting errors, post them. If your outputs are not correct, show a sample run and describe how the results are not correct. There's no struggle there, just do it.

  8. #8
    Junior Member
    Join Date
    Feb 2014
    Posts
    19
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: problem with calculator

    i added this part
    public static void main (String[] args)
    {
    Arithemtic calculator = new Arithmetic();
    calculator.isBalance();
    }
    but it says class, interface, or enum expected
    this is the main program do i need to add anything else to it so it runs?

  9. #9
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: problem with calculator

    Where did you add those lines of code? They need to be inside the {}s that enclose the class's code.
    If you don't understand my answer, don't ignore it, ask a question.

  10. #10
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: problem with calculator

    After 30-40 hours of instruction, you should know how to add methods to a class, especially the main() method. It looks like you haven't been paying attention. Refer to your notes, your textbook, other examples.

  11. #11
    Junior Member
    Join Date
    Feb 2014
    Posts
    19
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: problem with calculator

    yeah my bad i did it right this time and it shows me
    constructor Arithmetic in class stackscalc.Arithmetic cannot be applied to given types;
    required: java.lang.String
    found: no arguments
    reason: actual and formal argument lists differ in length

  12. #12
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: problem with calculator

    The error message is clear. The Arithmetic() constructor requires a String argument, the main() method you wrote calls Arithmetic() with no argument. Again, this error is one you should have seen and solved several times by now.

    The problem you said you were having in your first post is making less and less sense. You haven't gotten that far, and you're having trouble getting code that will compile and run. Keep working those errors, come back when you get stuck.

  13. #13
    Junior Member
    Join Date
    Feb 2014
    Posts
    19
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: problem with calculator

    ok guys so i changed the code and i compiled and didn t find any mistakes.but when i run it it shows me this ( i try to run it in an online compiler site )
    Compiling the source code....
    $javac Calculator.java 2>&1
    Note: Calculator.java uses unchecked or unsafe operations.
    Note: Recompile with -Xlint:unchecked for details.

    Executing the program....
    $java -Xmx128M -Xms16M Calculator
    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
    at Calculator.main(Calculator.java:84)
    import java.util.StringTokenizer;
    import java.util.Stack;
     
    public class Calculator {
     
           static int precedence(char op) {
                  switch(op) {
                  case '+' :
                  case '-' : 
                           return 5;
                  case '*' :
                  case '/' :
                           return 10;
                  default :
                           throw new IllegalArgumentException("invalid operator");
                   }
             }
           public static String infixToPostfix(String infix) {
                  StringTokenizer tokenizer = new StringTokenizer (infix);
                  String postfix = "";
                  Stack opStack = new Stack ();
     
                  while (tokenizer.hasMoreTokens()) {
                         String token = tokenizer.nextToken();
                         char c = token.charAt(0);
                         if (Character.isDigit(c)){
                                postfix +=(token + " ");
                         }
                         else {
                                 while (!opStack.empty()){
                                        char top = ((Character)opStack.peek()).charValue();
                                        if (precedence(top) >= precedence(c)) {
                                                postfix += (top + " ");
                                                opStack.pop();
                                         }
                                         else {
                                                break;
                                               }
                                         }
                                         opStack.push(new Character (c));
                              }
                          }
     
                   while (!opStack.empty()) {
                          char top = ((Character)opStack.pop()).charValue();
                          postfix += (top + " ");
                    }
                    return postfix;
            }
     
         public static int evalPostfix(String postfix) {
                  StringTokenizer tokenizer = new StringTokenizer(postfix);
                  Stack valStack = new Stack();
     
                  while(tokenizer.hasMoreTokens()) {
                         String token = tokenizer.nextToken();
                         char c = token.charAt(0);
                         if (Character.isDigit(c)) {
                                valStack.push(new Integer(token));
                          }
                          else {
                                  int rightVal = ((Integer)valStack.pop()).intValue();
                                  int leftVal = ((Integer)valStack.pop()).intValue();
                                  int rslt;
     
                                  switch(c) {
                                  case '+' : rslt = leftVal + rightVal;break;
                                  case '-' : rslt = leftVal - rightVal;break;
                                  case '*' : rslt = leftVal * rightVal;break;
                                  case '/' : rslt = leftVal + rightVal;break;
                                  default:
                                         throw new IllegalArgumentException("invalid postfix expression");
                                    }
                                   valStack.push(new Integer(rslt));
                                }
                         }
                     int rslt = ((Integer)valStack.pop()).intValue();
                     if (!valStack.empty()){
                              throw new IllegalArgumentException("invalid postfix expression");
                      }
                          return rslt;
              }
          public static void main(String[] args)  {
                 String infix = args[0];
                 String postfix = infixToPostfix(infix); 
                 System.out.println("postfix"+postfix);
                 int value = evalPostfix(postfix);
                 System.out.println("value: " + value);
             }
    }

  14. #14
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: problem with calculator

    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
    at Calculator.main(Calculator.java:84)
    At line 84 the code uses an invalid index with an array. Since the index is 0, the array must be empty.
    The code should test the size of the array before trying to index into it. The .length attribute will give you the array's size.


    What code is at line 84?
    If you don't understand my answer, don't ignore it, ask a question.

  15. #15
    Junior Member
    Join Date
    Feb 2014
    Posts
    19
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: problem with calculator

    i copied paste it wrong from my wordpad!sorry but i m very tired i ve trying this thing for hours.now i think i pasted right!

  16. #16
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: problem with calculator

    .now i think i pasted right!
    Sorry, I don't understand what you changed. Please explain.
    If you don't understand my answer, don't ignore it, ask a question.

  17. #17
    Junior Member
    Join Date
    Feb 2014
    Posts
    19
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: problem with calculator

    i added these at the start
    import java.util.StringTokenizer;
    import java.util.Stack;
    forgot to paste them.now it compiles

  18. #18
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: problem with calculator

    What about the execution error posted in #13 and #14?
    If you don't understand my answer, don't ignore it, ask a question.

  19. #19
    Junior Member
    Join Date
    Feb 2014
    Posts
    19
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: problem with calculator

    ah yeah i understand what u meant!thanx!sorry but i m really dizzy and english is not my main language!

  20. #20
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: problem with calculator

    All fixed then?

  21. #21
    Junior Member
    Join Date
    Feb 2014
    Posts
    19
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: problem with calculator

    yes now i have another question if you don t mind!i have a code for an infix post fix and evaluation as a calculator
    here is the code.it compiles its ok
     // Stack for numbers: 'values'
            Stack<Integer> values = new Stack<Integer>();
     
            // Stack for Operators: 'ops'
            Stack<Character> ops = new Stack<Character>();
     
            for (int i = 0; i < tokens.length; i++)
            {
                 // Current token is a whitespace, skip it
                if (tokens[i] == ' ')
                    continue;
     
                // Current token is a number, push it to stack for numbers
                if (tokens[i] >= '0' && tokens[i] <= '9')
                {
                    StringBuffer sbuf = new StringBuffer();
                    // There may be more than one digits in number
                    while (i < tokens.length && tokens[i] >= '0' && tokens[i] <= '9')
                        sbuf.append(tokens[i++]);
                    values.push(Integer.parseInt(sbuf.toString()));
                }
     
                // Current token is an opening brace, push it to 'ops'
                else if (tokens[i] == '(')
                    ops.push(tokens[i]);
     
                // Closing brace encountered, solve entire brace
                else if (tokens[i] == ')')
                {
                    while (ops.peek() != '(')
                      values.push(applyOp(ops.pop(), values.pop(), values.pop()));
                    ops.pop();
                }
     
                // Current token is an operator.
                else if (tokens[i] == '+' || tokens[i] == '-' ||
                         tokens[i] == '*' || tokens[i] == '/')
                {
                    // While top of 'ops' has same or greater precedence to current
                    // token, which is an operator. Apply operator on top of 'ops'
                    // to top two elements in values stack
                    while (!ops.empty() && hasPrecedence(tokens[i], ops.peek()))
                      values.push(applyOp(ops.pop(), values.pop(), values.pop()));
     
                    // Push current token to 'ops'.
                    ops.push(tokens[i]);
                }
            }
     
            // Entire expression has been parsed at this point, apply remaining
            // ops to remaining values
            while (!ops.empty())
                values.push(applyOp(ops.pop(), values.pop(), values.pop()));
     
            // Top of 'values' contains result, return it
            return values.pop();
        }
     
        // Returns true if 'op2' has higher or same precedence as 'op1',
        // otherwise returns false.
        public static boolean hasPrecedence(char op1, char op2)
        {
            if (op2 == '(' || op2 == ')')
                return false;
            if ((op1 == '*' || op1 == '/') && (op2 == '+' || op2 == '-'))
                return false;
            else
                return true;
        }
     
        // A utility method to apply an operator 'op' on operands 'a' 
        // and 'b'. Return the result.
        public static int applyOp(char op, int b, int a)
        {
            switch (op)
            {
            case '+':
                return a + b;
            case '-':
                return a - b;
            case '*':
                return a * b;
            case '/':
                if (b == 0)
                    throw new
                    UnsupportedOperationException("Cannot divide by zero");
                return a / b;
            }
            return 0;
        }
     
        // Driver method to test above methods
        public static void main(String[] args)
        {
            System.out.println(EvaluateString.evaluate("10 + 2 * 6"));
            System.out.println(EvaluateString.evaluate("100 * 2 + 12"));
            System.out.println(EvaluateString.evaluate("100 * ( 2 + 12 )"));
            System.out.println(EvaluateString.evaluate("100 * ( 2 + 12 ) / 14"));
        }
    }
    now how can i make it to ask the user to put a string to evaluate?as an input i mean
    i must add input scanner etc then ask the user to input the string and then i name it like for example a
    and i just add a.EvaluateString? or a.evaluate?

  22. #22
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: problem with calculator

    how can i make it to ask the user to put a string
    Some choices:
    The Scanner class has easy to use methods for reading user input.
    The JOptionPane class has methods that display a dialog window and accept user input that is returned.
    a.EvaluateString? or a.evaluate?
    If a is a String object, it will have to be passed to a method as a parameter: theMethod(a)
    If you don't understand my answer, don't ignore it, ask a question.

  23. #23
    Junior Member
    Join Date
    Feb 2014
    Posts
    19
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: problem with calculator

    scanner class is more preferable.no need for joptionpane
    as for the string it will be something like something like
    system.out.println("give numbers");
    String input = scan.nextLine();
    EvaluateString.evaluate(input);
    is that correct?

  24. #24
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: problem with calculator

    is that correct?
    It looks possible. You need to add it to the program, compile it and execute it to see if it does what you want.
    If you don't understand my answer, don't ignore it, ask a question.

  25. #25
    Junior Member
    Join Date
    Feb 2014
    Posts
    19
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: problem with calculator

    i tried to compiled it again and now it says provided class name is invalid.how did this happen?are online compilers trustworthy?

Page 1 of 2 12 LastLast

Similar Threads

  1. Infix calculator problem
    By cubertron in forum What's Wrong With My Code?
    Replies: 3
    Last Post: December 2nd, 2011, 07:32 AM
  2. Calculator layout problem
    By Choiseymitsu in forum What's Wrong With My Code?
    Replies: 2
    Last Post: April 28th, 2011, 08:04 AM
  3. [SOLVED] Another Calculator Problem
    By The_Mexican in forum What's Wrong With My Code?
    Replies: 0
    Last Post: December 4th, 2010, 03:31 PM
  4. Calculator problem
    By The_Mexican in forum What's Wrong With My Code?
    Replies: 10
    Last Post: December 4th, 2010, 01:01 PM
  5. Problem in implementing mortgage calculator
    By American Raptor in forum AWT / Java Swing
    Replies: 1
    Last Post: April 1st, 2009, 02:09 PM

Tags for this Thread