-1

So I am working on a PostFix calculator that is used in command line for a class project, and I am having a little trouble on developing a memory for it. I have been told to create a hashMap and I have researched it and understand the basics of it. I have the calculating method working, but what I am having trouble trying to implement a way for the user to declare variables. For example this what the user should be able to do:

> a = 3 5 + 1 -
 7
> bee = a 3 *
 21
> a bee +
 28
> bee 3 %
 0
> a = 4
 4
> 57
 57
> 2 c +
 c not found
> mem
 a: 4
 bee: 21
> exit

As you can see the user can declare variables in the format " =" My problem is, that I am not really sure how to Implement the hashMap, I have tried doing it by setting the variable name for the hashmap by getting it from an array list, and getting the integer value from it by getting the return value from my compute method, but all I get is this error:

>Exception in thread "main" java.lang.NumberFormatException: For input string: "
Error"
        at java.lang.NumberFormatException.forInputString(Unknown Source)
        at java.lang.Integer.parseInt(Unknown Source)
        at java.lang.Integer.parseInt(Unknown Source)
        at Program6.main(Program6.java:42)

Here is my code currently:

import java.util.*;
import java.io.*;
public class Program6
{
    private static HashMap<String,Integer> memory = new HashMap<>();
    public static void main(String args[])
    {
        System.out.println("Servando Hernandez");
        System.out.println("RPN command line calculator");
        Scanner scan = new Scanner(System.in);
        System.out.print(">");
        while(scan.hasNextLine())
        {
            System.out.print("> ");
            String a = scan.nextLine(); 
            String b = "quit";
            String c = "mem";
            String d = "clear";

            if(a.equals(b))
            { 
                System.exit(0);
            }
            else
            {
                System.out.println(compute(a));
            }
            System.out.print(">");

            List<String> list = new ArrayList<String>();
            if(!a.isEmpty())
            {
                StringTokenizer var = new StringTokenizer(a);
                while(var.hasMoreTokens())
                {
                    list.add(var.nextToken());
                }
            }
            int pos = 0;
            if (compute(a) != null)
            {
                pos = Integer.parseInt(compute(a));
            }



            memory.put(list.get(list.size()-1),pos);


        }   


    }



    public static String compute(String input)
    {
        List<String> processedList = new ArrayList<String>();
        if (!input.isEmpty()) 
        {
            String myRegex = "[^a-zA-Z]";
            StringTokenizer st = new StringTokenizer(input);
            while (st.hasMoreTokens())
            {
                processedList.add(st.nextToken());
                processedList.remove(myRegex);
                processedList.remove("=");

            }
        } 
        else
        {
            return "Error";
        }
        Stack<String> tempList = new Stack<String>();

        Iterator<String> iter = processedList.iterator();

        while (iter.hasNext())
            {
                String temp = iter.next();
                if (temp.matches("[0-9]*"))
                    {

                    tempList.push(temp);
                    }
                    else if (temp.matches("[*-/+]")) 
                    {

                        if (temp.equals("*")) 
                        {
                            int rs = Integer.parseInt(tempList.pop());
                            int ls = Integer.parseInt(tempList.pop());
                            int result = ls * rs;
                            tempList.push("" + result);
                        } 
                        else if (temp.equals("-")) 
                        {
                            int rs = Integer.parseInt(tempList.pop());
                            int ls = Integer.parseInt(tempList.pop());
                            int result = ls - rs;
                            tempList.push("" + result);
                        } 
                        else if (temp.equals("/")) 
                        {
                            int rs = Integer.parseInt(tempList.pop());
                            int ls = Integer.parseInt(tempList.pop());
                            int result = ls / rs;
                            tempList.push("" + result);
                        } 
                        else if (temp.equals("+")) 
                        {
                            int rs = Integer.parseInt(tempList.pop());
                            int ls = Integer.parseInt(tempList.pop());
                            int result = ls + rs;
                            tempList.push("" + result);
                        }

                    }
                    else
                    {
                        return "Error";
                    }
            }

        return tempList.pop();
    }
}

Does anyone know how i can make the hashMap memory on the post fix calculator work to where the user can assign variables and be able to call them back, or a better way to approach this?

Dayman
  • 67
  • 1
  • 7
  • What exactly are you trying to put in the hashmap? – ryekayo Apr 03 '15 at 15:06
  • I am trying to store the users answers. The user is able to declare his own variable kind of like what I showed above in the format of "variable = value". But I am stuck on how to make that work – Dayman Apr 03 '15 at 15:15
  • 1
    You should create a [MCVE](http://stackoverflow.com/help/mcve). – StackFlowed Apr 03 '15 at 15:26

2 Answers2

0

Your problem is you are adding "Error" from you else clause in the compute method and then trying to parse it as a int.

public static String compute(String input)
{
    List<String> processedList = new ArrayList<String>();
    if (!input.isEmpty()) 
    {
        String myRegex = "[^a-zA-Z]";
        StringTokenizer st = new StringTokenizer(input);
        while (st.hasMoreTokens())
        {
            processedList.add(st.nextToken());
            processedList.remove(myRegex);
            processedList.remove("=");

        }
    } 
    else
    {
        return "Error"; //-->> problem 
    }

Parsing it as an int. This point compute(a) will not be null as it has "Error". Next step you are trying to parse it as an int.

if (compute(a) != null)
{
    pos = Integer.parseInt(compute(a));
}

You can change your code as

if (compute(a) != null && !compute(a).equals("Error"))
{
    pos = Integer.parseInt(compute(a));
}

Also you should try you put your Integer.parseInt() code in a try catch.

StackFlowed
  • 6,664
  • 1
  • 29
  • 45
  • Right, but my program returns error because I have not been able to find a way to remove the user entered variable(since I don't know before hand) before it goes into my compute function. – Dayman Apr 03 '15 at 15:18
  • All I'm saying is don't try and parse that to an int. When you try to do Integer.parseInt("Error"); //--> This throws a NumberFormatException. Which you don't want. – StackFlowed Apr 03 '15 at 15:20
  • Okay so does that mean I should remove the error returns and try to parse the variable out to store it in a hashmap, then after computing my calculation store the result in my hashmap with my variable? – Dayman Apr 03 '15 at 15:47
0

Your HashMap can be used to store the variable names and their values. The key for the map will be the variable name, and the value is the number assigned to it. You currently have Integer but you might want something that handles decimals if you're going to allow things like a = 10 3 /.

In your compute(..) method you expect the input to be of the form var = <calculation> so you should first parse out the variable name which will be the key used in the hashmap memory, and after computing the calculation, store that result with memory.put(var,result);.

When computing the <calculation> part, if a variable name is encountered, look it up to find its value using memory.get(var) and use that value in the computation. With a postfix calculator, you just have to get the 2 values, followed by the operation and perform the math. The result of that is the first value of the next pair to operate on, and so on until you run out of operations and finally assign the result to the variable.

Always Learning
  • 5,510
  • 2
  • 17
  • 34