2015-02-11 109 views
-1

我想創建一個while循環作爲一個方法在一個數據解釋器,需要一個條件,而條件爲真執行語句的主體,然後返回值,一旦條件不再是真正的。如果它不執行,那麼它返回0.我遇到的問題是我不明白如何讓while循環執行語句的主體。這是我到目前爲止,我需要一個正確的方向,以我在這裏缺少的東西:while循環與用戶輸入

public class WhileStatement<b> extends Statement { 

private final Expression condition; 
private final Statement body; 


/** 
* @param c the condition for the while loop 
* @param b the body of the loop 
*/ 
public WhileStatement(Expression c, Statement b) { 

this.body = b; 
this.condition = c; 



} 

/** 
* Interpret this statement, returning the resulting value. 
* 
* @param env the current environment 
* 
* @return The integer value from the statement that is the loop 
*   body when it is last executed, or IntegerValue 0 if the 
*   loop never executes. 
*/ 
@Override 
public IntegerValue interpret(Environment env) { 

    IntegerValue cond = condition.interpret(env); 
    IntegerValue bod = body.interpret(env); 



    while (cond.equals(true)) { 
     return bod; 

    } 

    return new IntegerValue(0); 
    } 

謝謝你的幫助。

+0

你所說的「執行機構」是什麼意思?什麼是'Statement'類型?什麼是'Expression'類型?它們是來自java.beans還是你自己的東西?什麼是「IntegerValue」? – RealSkeptic 2015-02-11 20:46:13

+0

你如何評估病情..?是什麼使它成爲真假?什麼是聲明?它是Runnable類型嗎?如果不是,「執行聲明」的含義是什麼?請更具體一些。 – 2015-02-11 21:06:37

+0

'cond.equals(true)'這怎麼可能工作? – 2015-02-11 21:11:26

回答

0

你應該更加努力地描述你的代碼!

假設至少知道你在做什麼,我明白你的問題:

IntegerValue cond = condition.interpret(env); 
IntegerValue bod = body.interpret(env); 

IntegerValue result = new IntegerValue(0); 

while (cond.equals(true)) { 

    // execute whatever you wanted here in whatever way you do it 
    result = bod; 

} 

return bod;