那里。我在android中使用eval()函数时遇到问题。 它说尝试在空对象引用上调用接口方法'javax.script.Bindings javax.script.ScriptEngine.eval(java.lang.String)'。 我看过这个主题,似乎我有一些未初始化的东西。但是,我检查了我的代码,但找不到它。 请帮帮我:)。
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class MainActivity extends AppCompatActivity {
private TextView tvScreen;
private TextView tvHistory;
private static ScriptEngine engine;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvScreen = (TextView) findViewById(R.id.screen);
tvHistory = (TextView) findViewById(R.id.history);
engine = new ScriptEngineManager().getEngineByName("JavaScript");
}
public void expressionEdit(View view) {
if (tvScreen.getText().toString().equals("0")) {
tvScreen.setText("");
}
switch (view.getId()) {
case R.id.number1:
tvScreen.append("1");
break;
case R.id.number2:
tvScreen.append("2");
break;
case R.id.number3:
tvScreen.append("3");
break;
case R.id.number4:
tvScreen.append("4");
break;
case R.id.number5:
tvScreen.append("5");
break;
case R.id.number6:
tvScreen.append("6");
break;
case R.id.number7:
tvScreen.append("7");
break;
case R.id.number8:
tvScreen.append("8");
break;
case R.id.number9:
tvScreen.append("9");
break;
case R.id.number0:
tvScreen.append("0");
break;
case R.id.buttonDot:
tvScreen.append(".");
break;
case R.id.buttonPlus:
tvScreen.append("+");
break;
case R.id.buttonMinus:
tvScreen.append("-");
break;
case R.id.buttonTime:
tvScreen.append("*");
break;
case R.id.buttonDivide:
tvScreen.append("/");
break;
case R.id.buttonLeftP:
tvScreen.append("(");
break;
case R.id.buttonRightP:
tvScreen.append(")");
break;
case R.id.number00:
tvScreen.append("00");
break;
case R.id.buttonPercent:
tvScreen.append("%");
break;
case R.id.buttonAC:
tvScreen.setText("0");
tvHistory.setText("");
break;
case R.id.delete:
String temp = tvScreen.getText().toString();
if (temp.length()>1){
tvScreen.setText(temp.substring(0,temp.length()-1));
}
if (temp.length()==1){
tvScreen.setText("0");
}
break;
}
}
public void equalClicked(View view) {
tvHistory.setText(tvScreen.getText().toString()+"=");
String executableExp = expressionProcessor(tvScreen.getText().toString());
try{
String result = String.valueOf(engine.eval("1+1"));
//String result = String.valueOf(engine.eval(executableExp));
tvScreen.setText(result);
} catch (Exception e) {
Log.i("Error",e.getMessage());
tvHistory.setText("Error");
}
}
public String expressionProcessor(String originalExp){
String executableExp;
executableExp = originalExp.replaceAll("%","/100");
return executableExp;
}
}