Android studio 是否可以通过将条件放在一个字段中得到答案
我对编码是新手。我在Android Studio中制作了一个应用程序,用户在该字段中输入一个简单的公式(如5*2/5+6或其他…),然后得到答案。我在考虑编辑文本字段。有可能这样做吗 我发现了这个解析代码:(没有测试,但应该可以正常工作)Android studio 是否可以通过将条件放在一个字段中得到答案,android-studio,Android Studio,我对编码是新手。我在Android Studio中制作了一个应用程序,用户在该字段中输入一个简单的公式(如5*2/5+6或其他…),然后得到答案。我在考虑编辑文本字段。有可能这样做吗 我发现了这个解析代码:(没有测试,但应该可以正常工作) 现在可以对输出执行任何操作,例如,将其显示在某处。是,这是可能的。不,这不是魔法。程序员必须继续编程。:)非常感谢。怎么做? public static double eval(final String str) { return new Object
现在可以对输出执行任何操作,例如,将其显示在某处。是,这是可能的。不,这不是魔法。程序员必须继续编程。:)非常感谢。怎么做?
public static double eval(final String str) {
return new Object() {
int pos = -1, ch;
void nextChar() {
ch = (++pos < str.length()) ? str.charAt(pos) : -1;
}
boolean eat(int charToEat) {
while (ch == ' ') nextChar();
if (ch == charToEat) {
nextChar();
return true;
}
return false;
}
double parse() {
nextChar();
double x = parseExpression();
if (pos < str.length()) throw new RuntimeException("Unexpected: " + (char)ch);
return x;
}
// Grammar:
// expression = term | expression `+` term | expression `-` term
// term = factor | term `*` factor | term `/` factor
// factor = `+` factor | `-` factor | `(` expression `)`
// | number | functionName factor | factor `^` factor
double parseExpression() {
double x = parseTerm();
for (;;) {
if (eat('+')) x += parseTerm(); // addition
else if (eat('-')) x -= parseTerm(); // subtraction
else return x;
}
}
double parseTerm() {
double x = parseFactor();
for (;;) {
if (eat('*')) x *= parseFactor(); // multiplication
else if (eat('/')) x /= parseFactor(); // division
else return x;
}
}
double parseFactor() {
if (eat('+')) return parseFactor(); // unary plus
if (eat('-')) return -parseFactor(); // unary minus
double x;
int startPos = this.pos;
if (eat('(')) { // parentheses
x = parseExpression();
eat(')');
} else if ((ch >= '0' && ch <= '9') || ch == '.') { // numbers
while ((ch >= '0' && ch <= '9') || ch == '.') nextChar();
x = Double.parseDouble(str.substring(startPos, this.pos));
} else if (ch >= 'a' && ch <= 'z') { // functions
while (ch >= 'a' && ch <= 'z') nextChar();
String func = str.substring(startPos, this.pos);
x = parseFactor();
if (func.equals("sqrt")) x = Math.sqrt(x);
else if (func.equals("sin")) x = Math.sin(Math.toRadians(x));
else if (func.equals("cos")) x = Math.cos(Math.toRadians(x));
else if (func.equals("tan")) x = Math.tan(Math.toRadians(x));
else throw new RuntimeException("Unknown function: " + func);
} else {
throw new RuntimeException("Unexpected: " + (char)ch);
}
if (eat('^')) x = Math.pow(x, parseFactor()); // exponentiation
return x;
}
}.parse();
}
EditText inputField = findViewById(R.id.your_id_here);
String inputText = inputField.getText().toString();
double output = eval(inputText);