首页 > 解决方案 > 使用hashmap java将两个键的值与第三个键相加

问题描述

我正在用 Jflex 和 CUP 制作编译器。我试图让我的编译器使这个例子工作。

 start

    x=1;
    y=2;
    z=x+y;
    print(z);

    end

我正在努力将x+y之和的值分配给z

这是我的代码的一部分


    action code {:
        
        public static HashMap<String, Object> hm = new HashMap<>();
        
        
        public static void Put(String identifier, Object value) {
            hm.put(identifier, value);
        }
    
    
                               
        public static Object Get(String identifier) {
            return hm.get(identifier);
        }
       
        public static void Show(String value) {
            System.out.println("Result: " +  value);
            System.out.println("END.");
        }
        
    :};

我的语法是这样的


    statement::= IDENTIFIER:v expr:e
    
                {: RESULT = Get((String)v); :}
            | IDENTIFIER:v = expr:e {: Put((String)v, e); :}
            | IDENTIFIER:v1 = IDENTIFIER:v2 {: Put((String)v1, Get((String)v2)); :} 
            | PRINT LPARENTESIS IDENTIFIER:v RPARENTESIS  {: System.out.println(Get((String)v)); :}                 
           | IDENTIFIER:v1 = IDENTIFIER:v2 SUM IDENTIFIER:v3 {: Put((String)v1, Get((String)v2+v3)); :} 
                    |expr:e
            |
    ;
    
    expr ::= expr:e1 SUM expr:e2
            {: RESULT ASIGN new Integer(e1.intValue() + e2.intValue());   :}
            | expr:e1 MINUS expr:e2
            {: RESULT = new Integer(e1.intValue() - e2.intValue()); :}
            | NUMBER:n
            {: RESULT = n;  System.out.println(n);  :}
            | LPARENTESIS expr:e RPARENTESIS 
            {: RESULT = e; :}
            ;


符号

SUM = "+" 
LPARENTESIS  = "(" 
RPARENTESIS = ")" 
MINUS= "-" 
ASIGN = "="`



 | IDENTIFIER:v1 = IDENTIFIER:v2 + IDENTIFIER:v3 {: Put((String)v1, Get((String)v2+v3)); :}

这是我努力添加 v2 和 v3 的值并将其存储在 v1 中的地方

我在java中编程不多,需要帮助谢谢

标签: javahashmapsumcompiler-constructioncup

解决方案


推荐阅读