Page 2 of 3 FirstFirst 123 LastLast
Results 21 to 40 of 50
  1. #21
    Speculant is offline Member
    Join Date
    Feb 2012
    Posts
    26
    Rep Power
    0

    Default Re: Need help on a calculator project

    can I pass x,y, and z from expressiondialog to calculator through assignop, like I do with hashMap?

  2. #22
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,620
    Rep Power
    23

    Default Re: Need help on a calculator project

    Do you mean you want to pass the values of x, y and z to a method or constructor as parameters?
    Yes you could do that.

  3. #23
    Speculant is offline Member
    Join Date
    Feb 2012
    Posts
    26
    Rep Power
    0

    Default Re: Need help on a calculator project

    I made some progress, entering something other than x, y, z, a number, or a math symbol gives the user an error. Keys x, y, and z are all given a value of zero in the hashMap at the start of the program, and if x, y, or z is entered, it prints their value on the screen.

    Now, I am not sure how to assign the x entered and the value on the other side of the = as a key/value pair in the hashMap. For example, if x = 2 is entered, nothing happens. I have hashMap.put(result, term) to assign the result (which would be x) and the term (which would be the number) as the key and the value, respectively, but it doesn't seem to be working (line 34, Calculator.java).

    Calculator.java

    Java Code:
    import java.util.*;
    public class Calculator
    {
       String expstring;
       int cursor;
    
       public Calculator()
       {
          expstring = null;
       }
         
     
       public Calculator(String instring)
       {
        expstring = instring;
        cursor = 0;
       }
    
       public void setExpression(String estring)
       {
          expstring = estring;
          cursor = 0;
       }
    
       public float assignmentOp(HashMap hashMap, float x, float y, float z)
       {
          cursor = 0;
          float result = evalExp();
          while (nextOperator('='))
          {
             char operator = getOperator();
             float term = evalExp();
             if (operator == '=' && result == x || result == y || result == z)
                hashMap.put(result, term);
             else
                System.err.println("Only variables x, y or z may be allowed to be assigned.");
          }
          return result;
       }
    
       public float evalExp()
       {
          if (expstring == null)
          {
             System.err.println("There is no expression to evaluate.");
             System.err.println("Call setExpression() before calling getResult().");
             return 0;
          }
    
          float result = evalTerm();
          while (nextOperator('+'))
          {
             char operator = getOperator();
             float term = evalTerm();
             if (operator == '+')
                result = result + term;
             else
                System.err.println("Invalid operator: " + operator);
          }
          while (nextOperator('-'))
          {
             char operator = getOperator();
             float term = evalTerm();
             if (operator == '-')
                result = result - term;
             else
                System.err.println("Invalid operator: " + operator);
          }
          return result;
       }
     
       private float evalTerm()
       {
          float result = getOperand();
          while (nextOperator('*'))
          {
             char operator = getOperator();
             float term = getOperand();
             if (operator == '*')
                result = result * term;
             else
                break;
          }
          while (nextOperator('/'))
          {
             char operator = getOperator();
             float term = getOperand();
             if (operator == '/')
                result = result / term;
             else
                break;
          }
          return result;
       } 
     
       private float getOperand()
       {
          if (cursor >= expstring.length())
             return 0;
          String opstring = "";
          char nextchar = expstring.charAt(cursor);
          if (nextchar == '-')
          {
             opstring = opstring + '-';
             cursor++;
             nextchar = expstring.charAt(cursor);
          }
          while (cursor < expstring.length() && !isOperator(nextchar))
          {
             opstring = opstring + nextchar;
             cursor++;
             if (cursor < expstring.length())
                nextchar = expstring.charAt(cursor);
          }
          return Float.parseFloat(opstring);
       }
     
       private char getOperator()
       {
          char operator = expstring.charAt(cursor);
          cursor++;
          return operator;
       }
       
       private boolean nextOperator(char op)
       {
          if (cursor < expstring.length() && expstring.charAt(cursor) == op)
             return true;
          else
             return false;
       }
       
       private boolean isOperator(char c)
       {
          String opset = "+*-/=";
          return (opset.indexOf(c) >= 0);
       }
    }
    ExpressionDialog.java

    Java Code:
    import java.util.*;
    import java.io.*;
    
    class ExpressionDialog
    {
       Scanner keyreader;
       Calculator calc;
       PrintStream logfile;
       HashMap hashMap = new HashMap();
       float x;
       float y;
       float z;
       
       public ExpressionDialog()
       {
          keyreader = new Scanner(System.in);
          calc = new Calculator();
       }
        
       public void run()
       {
          String expression;
          float result = 0;
          hashMap.put("x", 0.0);
          hashMap.put("y", 0.0);
          hashMap.put("z", 0.0);
          showMenu();
          expression = getNextExpression(); 
          while(!expression.equals("quit"))
          {
             if (expression.equals("log off") && (logfile != null))
             {
                logfile.close();
             }
             else if (expression.equals("log"))
             {
                //Not very clean, prompt should be on the same line as the user input
                //Also adds a space and => 0.0 at the start of the file, this isn't clean and ideally should be changed
                System.out.println("Enter in a filename");
                setLogFile(keyreader.next());           
             }
             else if (expression.equals("x"))
             {
               System.out.println("=> " + hashMap.get("x"));
             }
             else if (expression.equals("y"))
             {
               System.out.println("=> " + hashMap.get("y"));
             }
             else if (expression.equals("z"))
             {
               System.out.println("=> " + hashMap.get("z"));
             }
             else
             {
               calc.setExpression(expression);
              try
              {
              result = calc.assignmentOp(hashMap, x, y, z);
              System.out.println("=> " + result);
              if (logfile != null)
                {
                logfile.println(expression);
                logfile.println("=> " + result);
                }
              }
              catch (NumberFormatException e)
              {
                 System.out.println("Incorrect entry");
              }
              }
              expression = getNextExpression();       
          }
          if (logfile != null)
             logfile.close();
       }
    
       private String getNextExpression()
       {
          System.out.print("? ");
          return keyreader.nextLine();
       }
    
       private void showMenu()
       {
          System.out.println("<expression>      //Enter a simple arithmetic expression");
          System.out.println("log <filename>    //Turn on file logging to the specified output file");
          System.out.println("log off           //Turn file logging off");
          System.out.println("quit              //To terminate the program");
       }
       
       private void setLogFile(String filename)
       {
          try
          {
             logfile = new PrintStream(filename);
          }
          catch (Exception e)
          {
             System.out.println(e.getMessage());
          }  
       }
    
       public static void main(String[] args)
       {
          ExpressionDialog dialog = new ExpressionDialog();
          if (args.length > 0)
             dialog.setLogFile(args[0]);
          dialog.run();
       }
    }

  4. #24
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,620
    Rep Power
    23

    Default Re: Need help on a calculator project

    nothing happens.
    Please explain.
    If you don't know what the code is doing, try debugging it by adding printlns to show execution flow and the values of variables as they are changed and used.

  5. #25
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,620
    Rep Power
    23

    Default Re: Need help on a calculator project

    x = 2 is entered
    How do you execute the code for testing?
    I put the input in the code this way for easier testing:
    Java Code:
          keyreader = new Scanner("x = 23");  //System.in);
    And get this output:
    Running: F:\Java\jre6\bin\java.exe -classpath D:\JavaDevelopment;.;..\. -Xmx512M ExpressionDialog

    <expression> //Enter a simple arithmetic expression
    log <filename> //Turn on file logging to the specified output file
    log off //Turn file logging off
    quit //To terminate the program
    ? Incorrect entry x = 23
    ? Exception in thread "main" java.util.NoSuchElementException: No line found
    at java.util.Scanner.nextLine(Unknown Source)
    at ExpressionDialog.getNextExpression(ExpressionDialo g.java:221)
    at ExpressionDialog.run(ExpressionDialog.java:212)
    at ExpressionDialog.main(ExpressionDialog.java:249)

    0 error(s)
    What values should be preloaded into the Scanner class to test the code?

  6. #26
    Speculant is offline Member
    Join Date
    Feb 2012
    Posts
    26
    Rep Power
    0

    Default Re: Need help on a calculator project

    Sorry I didn't really explain.

    All of what I'm doing here takes place in assignmentOp, in Calculator.java.

    The item on the left side of the = is the "result" variable (which would be x in this case), and the item on the right side is the "term" variable (which would be a number or math expression). I am trying to assign the "result" as a key in hashMap and "term" as "result"'s value. For example, if the user entered "x = 10", x would be assigned as the key, and 10 would be assigned as x's value.

    To accomplish all this, I used "hashMap.put(result, term)" but instead of assigning x as a key and the number entered as it's value, it is giving me the same error as if I were to enter an illegal term, such as "asfassd".

    EDIT: You posted as I was typing, didn't get a chance to read your newest post until just now.

    Where did you put "keyreader = new Scanner("x = 23"); //System.in);" to test the code?
    And, what do you mean when you say "what values should be preloaded into the Scanner class to test the code?"
    Last edited by Speculant; 02-06-2012 at 10:31 PM.

  7. #27
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,620
    Rep Power
    23

    Default Re: Need help on a calculator project

    Did you see my post #25?
    How do I setup the input for the program?

    it is giving me the same error
    Can you post the full text of the error message?

  8. #28
    Speculant is offline Member
    Join Date
    Feb 2012
    Posts
    26
    Rep Power
    0

    Default Re: Need help on a calculator project

    Quote Originally Posted by Norm View Post
    Did you see my post #25?
    How do I setup the input for the program?
    When you run ExpressionDialog, you should see a ?, which is the prompt, where you can enter math expressions.

    Can you post the full text of the error message?
    When I enter "x = 10", the error the program sends back is "Incorrect entry", which is part of the program. There is a try/catch section where if the program runs into a numberformatexception error, it gives the user "Incorrect entry" instead of crashing.

  9. #29
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,620
    Rep Power
    23

    Default Re: Need help on a calculator project

    Can you create a String for testing the input?
    Here's what I now have. This replaces line 16:
    Java Code:
          keyreader = new Scanner("x\nz\nx = 23\ny = 22\nz = 21\n");//System.in);
    Fix the above line so the program works. This line does not work. See below.

    Here is what the code does with that input:
    Java Code:
    <expression>      //Enter a simple arithmetic expression
    log <filename>    //Turn on file logging to the specified output file
    log off           //Turn file logging off
    quit              //To terminate the program
    ? => x=1.0
    ? => x=3.0
    ? java.lang.NumberFormatException: For input string: "x"
    	at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
    	at java.lang.Float.parseFloat(Unknown Source)
    	at ExpressionDialog$Calculator.getOperand(ExpressionDialog.java:126)
    	at ExpressionDialog$Calculator.evalTerm(ExpressionDialog.java:85)
    	at ExpressionDialog$Calculator.evalExp(ExpressionDialog.java:60)
    	at ExpressionDialog$Calculator.assignmentOp(ExpressionDialog.java:37)
    	at ExpressionDialog.run(ExpressionDialog.java:204)
    	at ExpressionDialog.main(ExpressionDialog.java:255)
    Incorrect entry x = 23
    ? java.lang.NumberFormatException: For input string: "y"
    	at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
    	at java.lang.Float.parseFloat(Unknown Source)
    	at ExpressionDialog$Calculator.getOperand(ExpressionDialog.java:126)
    	at ExpressionDialog$Calculator.evalTerm(ExpressionDialog.java:85)
    	at ExpressionDialog$Calculator.evalExp(ExpressionDialog.java:60)
    	at ExpressionDialog$Calculator.assignmentOp(ExpressionDialog.java:37)
    	at ExpressionDialog.run(ExpressionDialog.java:204)
    	at ExpressionDialog.main(ExpressionDialog.java:255)
    Incorrect entry y = 22
    ? java.lang.NumberFormatException: For input string: "z"
    	at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
    	at java.lang.Float.parseFloat(Unknown Source)
    	at ExpressionDialog$Calculator.getOperand(ExpressionDialog.java:126)
    	at ExpressionDialog$Calculator.evalTerm(ExpressionDialog.java:85)
    	at ExpressionDialog$Calculator.evalExp(ExpressionDialog.java:60)
    	at ExpressionDialog$Calculator.assignmentOp(ExpressionDialog.java:37)
    	at ExpressionDialog.run(ExpressionDialog.java:204)
    	at ExpressionDialog.main(ExpressionDialog.java:255)
    Incorrect entry z = 21
    ? Exception in thread "main" java.util.NoSuchElementException: No line found
    	at java.util.Scanner.nextLine(Unknown Source)
    	at ExpressionDialog.getNextExpression(ExpressionDialog.java:226)
    	at ExpressionDialog.run(ExpressionDialog.java:216)
    	at ExpressionDialog.main(ExpressionDialog.java:255)

  10. #30
    Speculant is offline Member
    Join Date
    Feb 2012
    Posts
    26
    Rep Power
    0

    Default Re: Need help on a calculator project

    I didn't think the problem was in public ExpressionDialog(), and the line does the same thing as if I were to type in x, then z, then x = 23, then y = 22, then z = 21. Do you want me to fix it so that it doesn't give a NoSuchElementException error at the end?

  11. #31
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,620
    Rep Power
    23

    Default Re: Need help on a calculator project

    so that it doesn't give a NoSuchElementException error at the end
    That's not a problem right now. Your basic code is not working. What expressions/input does it work with?
    You need to call printStackTrace in the catch block to see what the error is.

  12. #32
    Speculant is offline Member
    Join Date
    Feb 2012
    Posts
    26
    Rep Power
    0

    Default Re: Need help on a calculator project

    I'm not sure how to implement printStackTrace into my program

  13. #33
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,620
    Rep Power
    23

    Default Re: Need help on a calculator project

    You call it in the catch block. Its a method of the Throwable class (Exception extends that).

    Do a Search here on the forum and you'll find lots of examples.

  14. #34
    Speculant is offline Member
    Join Date
    Feb 2012
    Posts
    26
    Rep Power
    0

    Default Re: Need help on a calculator project

    I think I isolated the problem to the assignmentOp function in Calculator.java. If I enter x = 1 into the prompt, the key x's value is changed to 10. This proves when the = is in the prompt, it runs through the if statement in the assingmentOp function, so now I just need to figure out how find out whether it is a x, y, or z that is entered and assign the x, y, or z the value that is entered after the =.

    Java Code:
    import java.util.*;
    public class Calculator
    {
       String expstring;
       int cursor;
    
       public Calculator()
       {
          expstring = null;
       }
         
     
       public Calculator(String instring)
       {
        expstring = instring;
        cursor = 0;
       }
    
       public void setExpression(String estring)
       {
          expstring = estring;
          cursor = 0;
       }
    
       public float assignmentOp(HashMap hashMap)
       {
          cursor = 0;
          float result = evalExp();
          while (nextOperator('='))
          {
             char operator = getOperator();
             float term = evalExp();
             if (operator == '=')
             {
               hashMap.put("x", 10);
             }
             else
                System.err.println("Only variables x, y or z may be allowed to be assigned.");
          }
          return result;
       }
    
       public float evalExp()
       {
          if (expstring == null)
          {
             System.err.println("There is no expression to evaluate.");
             System.err.println("Call setExpression() before calling getResult().");
             return 0;
          }
          float result = evalTerm();
          while (nextOperator('+'))
          {
             char operator = getOperator();
             float term = evalTerm();
             if (operator == '+')
                result = result + term;
             else
                System.err.println("Invalid operator: " + operator);
          }
          while (nextOperator('-'))
          {
             char operator = getOperator();
             float term = evalTerm();
             if (operator == '-')
                result = result - term;
             else
                System.err.println("Invalid operator: " + operator);
          }
          return result;
       }
     
       private float evalTerm()
       {
          float result = getOperand();
          while (nextOperator('*'))
          {
             char operator = getOperator();
             float term = getOperand();
             if (operator == '*')
                result = result * term;
             else
                break;
          }
          while (nextOperator('/'))
          {
             char operator = getOperator();
             float term = getOperand();
             if (operator == '/')
                result = result / term;
             else
                break;
          }
          return result;
       } 
     
       private float getOperand()
       {
          if (cursor >= expstring.length())
             return 0;
          String opstring = "";
          char nextchar = expstring.charAt(cursor);
          if (nextchar == '-')
          {
             opstring = opstring + '-';
             cursor++;
             nextchar = expstring.charAt(cursor);
          }
          while (cursor < expstring.length() && !isOperator(nextchar))
          {
             opstring = opstring + nextchar;
             cursor++;
             if (cursor < expstring.length())
                nextchar = expstring.charAt(cursor);
          }
          return Float.parseFloat(opstring);
       }
     
       private char getOperator()
       {
          char operator = expstring.charAt(cursor);
          cursor++;
          return operator;
       }
       
       private boolean nextOperator(char op)
       {
          if (cursor < expstring.length() && expstring.charAt(cursor) == op)
             return true;
          else
             return false;
       }
       
       private boolean isOperator(char c)
       {
          String opset = "+*-/=";
          return (opset.indexOf(c) >= 0);
       }
    }
    Java Code:
    import java.util.*;
    import java.io.*;
    
    class ExpressionDialog
    {
       Scanner keyreader;
       Calculator calc;
       PrintStream logfile;
       HashMap hashMap = new HashMap();
       
       public ExpressionDialog()
       {
          keyreader = new Scanner(System.in);
          calc = new Calculator();
       }
        
       public void run()
       {
          String expression;
          float result = 0;
          showMenu();
          expression = getNextExpression(); 
          hashMap.put("x", 0.0);
          hashMap.put("y", 0.0);
          hashMap.put("z", 0.0);
          while(!expression.equals("quit"))
          {
             if (expression.equals("log off") && (logfile != null))
             {
                logfile.close();
             }
             else if (expression.equals("log"))
             {
                //Not very clean, prompt should be on the same line as the user input
                //Also adds a space and => 0.0 at the start of the file, this isn't clean and ideally should be changed
                System.out.println("Enter in a filename");
                setLogFile(keyreader.next());           
             }
             else if (expression.equals("x"))
             {
               System.out.println("=> " + hashMap.get("x"));
             }
             else if (expression.equals("y"))
             {
               System.out.println("=> " + hashMap.get("y"));
             }
             else if (expression.equals("z"))
             {
               System.out.println("=> " + hashMap.get("z"));
             }
             else
             {
               calc.setExpression(expression);
              try
              {
              result = calc.assignmentOp(hashMap);
              System.out.println("=> " + result);
              if (logfile != null)
                {
                logfile.println(expression);
                logfile.println("=> " + result);
                }
              }
              catch (NumberFormatException e)
              {
                 System.out.println("Incorrect entry");
              }
              }
              expression = getNextExpression();       
          }
          if (logfile != null)
             logfile.close();
       }
    
       private String getNextExpression()
       {
          System.out.print("? ");
          return keyreader.nextLine();
       }
    
       private void showMenu()
       {
          System.out.println("<expression>      //Enter a simple arithmetic expression");
          System.out.println("log <filename>    //Turn on file logging to the specified output file");
          System.out.println("log off           //Turn file logging off");
          System.out.println("quit              //To terminate the program");
       }
       
       private void setLogFile(String filename)
       {
          try
          {
             logfile = new PrintStream(filename);
          }
          catch (Exception e)
          {
             System.out.println(e.getMessage());
          }  
       }
    
       public static void main(String[] args)
       {
          ExpressionDialog dialog = new ExpressionDialog();
          if (args.length > 0)
             dialog.setLogFile(args[0]);
          dialog.run();
       }
    }

  15. #35
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,024
    Blog Entries
    7
    Rep Power
    20

    Default Re: Need help on a calculator project

    Just a question: can you read this page now? I asked about not being able to read the blog pages but had no response from the gods yet (lazy bums ;-)

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  16. #36
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,620
    Rep Power
    23

    Default Re: Need help on a calculator project

    You still have not added the call to printStackTrace() to your catch block.
    You should have that while you are debugging the code. Its output will show you the exact problem and its location.

  17. #37
    Speculant is offline Member
    Join Date
    Feb 2012
    Posts
    26
    Rep Power
    0

    Default Re: Need help on a calculator project

    Jos, I can read your blog post now. I will look through it and try to fix this.

  18. #38
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,024
    Blog Entries
    7
    Rep Power
    20

    Default Re: Need help on a calculator project

    Quote Originally Posted by Speculant View Post
    Jos, I can read your blog post now. I will look through it and try to fix this.
    Ah, good! Maybe they have removed that restriction or maybe you have enough posts now (silly restriction ...); best of luck with the code in that blog article.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  19. #39
    Speculant is offline Member
    Join Date
    Feb 2012
    Posts
    26
    Rep Power
    0

    Default Re: Need help on a calculator project

    Update, I want to now be able to be able to assign a value to any variable the user enters, and also implement the ^ (power) sign as a math possibility. Would hashtables still be optimal for assigning any variable the user enters, or would parallel arrays be better?

  20. #40
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,024
    Blog Entries
    7
    Rep Power
    20

    Default Re: Need help on a calculator project

    Quote Originally Posted by Speculant View Post
    Update, I want to now be able to be able to assign a value to any variable the user enters, and also implement the ^ (power) sign as a math possibility. Would hashtables still be optimal for assigning any variable the user enters, or would parallel arrays be better?
    Did you read my blog article? The expression compiler can define new variables and do exponentiation too ...

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

Page 2 of 3 FirstFirst 123 LastLast

Similar Threads

  1. Need help with Calculator
    By Joshua4missions in forum New To Java
    Replies: 4
    Last Post: 12-10-2011, 02:44 AM
  2. Creating a project in eclipse from existing project
    By Suraiya in forum New To Java
    Replies: 1
    Last Post: 10-08-2011, 09:14 AM
  3. Help in a calculator
    By Ayannie in forum New To Java
    Replies: 6
    Last Post: 01-04-2011, 08:21 PM
  4. help with calculator
    By kalibballer in forum New To Java
    Replies: 8
    Last Post: 04-01-2009, 12:57 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •