2016-05-30 54 views
0

所以即時嘗試在我的simpleDB數據庫中實現加法運算符。我做了大部分工作,但我不知道如何添加2個部分。所以這將用於查詢數據庫,我想能夠添加左側和右側。什麼java方法可以用來做到這一點?因爲在simpleDB中沒有添加運算符。Java運算符是如何工作的?

這是我是如何實現的<運營商像現在我有

Constant lhsval = lhs.evaluate(s); 
     Constant rhsval = rhs.evaluate(s); 
    if (operator.equals("+")) { 
      // return ; 
      } 

我有左側和右側 所以當查詢看到的+號

if (operator.equals("<") && lhsval.compareTo(rhsval) < 0) { 
     return true; 
     } 

,它會添加並返回答案。但我不知道如何。當我實現了少於運算符時,我使用了comprateTo方法,並且當我使用等於運算符時使用了equals方法。我不知道我可以用加法operator.btw這是用java

不斷類

package simpledb.query; 

/** 
* The interface that denotes values stored in the database. 
* @author Edward Sciore 
*/ 
public interface Constant extends Comparable<Constant> { 

    /** 
    * Returns the Java object corresponding to this constant. 
    * @return the Java value of the constant 
    */ 
    public Object asJavaVal(); 
} 
+0

不是很清楚,你想串聯,將被髮送到一個數據庫中獲取記錄查詢的各個組成部分? –

+0

你有沒有試過'lhsval.concat(rhsval)' – Billydan

+0

無法使用concat,它沒有實現。多數民衆贊成什麼使這個硬大聲笑 – henryzo

回答

1

關係運算,例如比B下已經實現,因爲類型常量工具相媲美。

如果你想實現一個關係運算符,如A + B,則常數的類型必須實現這樣的類型可添加?我想是的,它必須。

Constant lhsval = lhs.evaluate(s); 
    Constant rhsval = rhs.evaluate(s); 
    if (operator.equals("+")) { 
     return lhsval.add(rhsval); 
    } 

可添加接口具有本合同:

interface Addable extends RelationalOperator { 
     Constant add(Constant lhs, Constant rhs);  
    } 

你必須決定附加運營商如何有工作(連擊,總之,依賴於恆亞型,...)

關於問題更新後編輯

一個簡單的實現是使用方法Object asJavaVal();如下:

Constant lhsval = lhs.evaluate(s); 
    Constant rhsval = rhs.evaluate(s); 
    if (operator.equals("+")) { 
     Object lhsObj = lhs.asJavaVal(); 
     Object rhsObj = lhs.asJavaVal(); 
     // here check for null and same type of lhs, rhs 
     ... 
     // now use typed implementation of + 
     if (lhsObj instanceof BigDecimal) 
      return new ConstantImpl(lhsval.add(rhsval)); 
     else if (lhsObj instanceof String) 
      return new ConstantImpl(lhsval + rhsval); 
     else if (lhsObj instanceof ...) 
      return new ConstantImpl(...); 
     else 
      throw new IllegalArgumentException("Not a valid type for + :"+ lhsObj.getClass()); 
    } 
+0

是的,這東西我有點難以遵循,除非我把你鏈接到有SimpleDB軟件包的站點,所以你可以在eclipse上運行它並查看所有代碼。但我懷疑任何人都想這樣做,大聲笑。感謝幫助 。生病看看你說什麼可以幫助我 – henryzo

+0

@henryzo我不保證我可以看到所有的代碼,但如果你想鏈接完整的實現simpleDB我會看看它。 – Aris2World

+0

http://csns.calstatela.edu/wiki/content/cysun/course_materials/cs422/simpledb你應該看看解析代碼和術語代碼 – henryzo

0

我認爲,這是更好地檢查lhsvalrhsval類型。之後,你可以通過asJavaVal獲取已知類型的值:

Constant lhsval = lhs.evaluate(s); 
Constant rhsval = rhs.evaluate(s); 
Constant res = null; 
if (operator.equals("+")) { 
    if (lhsval instanceof IntConstant) { 
     int sum = (Integer) lhsval.asJavaVal() + (Integer) rhsval.asJavaVal(); 
     res = new IntConstant(sum); 
    } else if (lhsval instanceof StringConstant) { 
     String sum = ((String) lhsval.asJavaVal()).concat((String) rhsval.asJavaVal()); 
     res = new StringConstant(sum); 
    } else { 
     throw new IllegalArgumentException("Unknown constant type"); 
    } 
} 
相關問題