如何将EditText中的求和表达式字符串转换为整数并获取结果
Hey there! Let's tackle this problem of turning a sum string (like "1+2+3+4") from your EditText into a calculated integer result. Here are two practical approaches you can use in your Android app:
1. Manual Parsing (Best for Simple Addition)
If your use case is just basic addition (no complex operations like multiplication or parentheses), manually splitting the string and summing up the values is straightforward and avoids any external dependencies.
Steps:
- Get the raw string from your EditText
- Remove any whitespace (in case users input spaces like "1 + 2 + 3")
- Split the string using
"+"as the delimiter - Iterate over each split part, convert it to an integer, and accumulate the sum
Example Code (Kotlin):
val editText = findViewById<EditText>(R.id.your_edit_text_id) val expression = editText.text.toString().replace(" ", "") // Remove spaces val numbers = expression.split("+") var sum = 0 try { for (numStr in numbers) { if (numStr.isNotEmpty()) { // Handle cases where expression starts/ends with "+" sum += numStr.toInt() } } // Now 'sum' holds the result, e.g., 10 for "1+2+3+4" Toast.makeText(this, "Result: $sum", Toast.LENGTH_SHORT).show() } catch (e: NumberFormatException) { // Handle invalid input (like non-numeric characters) Toast.makeText(this, "Invalid input!", Toast.LENGTH_SHORT).show() }
Example Code (Java):
EditText editText = findViewById(R.id.your_edit_text_id); String expression = editText.getText().toString().replace(" ", ""); String[] numbers = expression.split("\\+"); // Escape "+" since it's a regex special character int sum = 0; try { for (String numStr : numbers) { if (!numStr.isEmpty()) { sum += Integer.parseInt(numStr); } } Toast.makeText(this, "Result: " + sum, Toast.LENGTH_SHORT).show(); } catch (NumberFormatException e) { Toast.makeText(this, "Invalid input!", Toast.LENGTH_SHORT).show(); }
2. Using ScriptEngine (For More Complex Expressions)
If you plan to support more operations later (like subtraction, multiplication), using a script engine to evaluate the expression is a scalable solution. Note that on Android, you might need to add a dependency for full JavaScript engine support, or use the built-in one carefully.
Example Code (Java):
EditText editText = findViewById(R.id.your_edit_text_id); String expression = editText.getText().toString(); try { ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("JavaScript"); Object result = engine.eval(expression); if (result instanceof Integer) { int sum = (Integer) result; Toast.makeText(this, "Result: " + sum, Toast.LENGTH_SHORT).show(); } else if (result instanceof Double) { // Handle cases where result is a double (e.g., 5/2 = 2.5) int sum = ((Double) result).intValue(); Toast.makeText(this, "Result: " + sum, Toast.LENGTH_SHORT).show(); } } catch (ScriptException e) { Toast.makeText(this, "Invalid expression!", Toast.LENGTH_SHORT).show(); }
Note for Android:
Some older Android versions might have limited support for ScriptEngine. If you run into issues, consider adding the Rhino library to your build.gradle (Module level):
implementation 'org.mozilla:rhino:1.7.14'
Then initialize the engine with Rhino:
ScriptEngine engine = new org.mozilla.javascript.Context().initStandardObjects();
Key Notes to Remember
- Input Validation: Always add checks to handle invalid inputs (like letters, empty strings, or malformed expressions) to prevent crashes.
- Edge Cases: Test scenarios like empty EditText, expressions starting/ending with "+", or negative numbers (e.g., "-1+2+3") to make sure your code handles them correctly.
- Performance: Manual parsing is faster for simple addition, while ScriptEngine is better for complex math operations.
内容的提问来源于stack exchange,提问作者AbdallahBedo

